@ryuugg/stanza 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ryuugg/stanza",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "An opinionated code formatter for TypeScript.",
5
5
  "keywords": [
6
6
  "formatter",
package/src/cli.ts CHANGED
@@ -83,10 +83,19 @@ function help(): string {
83
83
  }
84
84
 
85
85
  function parseExplain(args: string[]): ExplainArguments | { error: string } {
86
- const targets = args.filter((arg) => arg !== "--no-braces");
87
- if (args.length - targets.length > 1) return { error: "--no-braces given twice" };
86
+ const delimiter = args.indexOf("--");
87
+ const optionArgs = delimiter < 0 ? args : args.slice(0, delimiter);
88
+ const literalLocations = delimiter < 0 ? [] : args.slice(delimiter + 1);
88
89
 
89
- const unexpected = targets.find((arg) => arg.startsWith("-")) ?? targets[1];
90
+ const optionTargets = optionArgs.filter((arg) => arg !== "--no-braces");
91
+ const noBracesCount = optionArgs.length - optionTargets.length;
92
+ if (noBracesCount > 1) return { error: "--no-braces given twice" };
93
+
94
+ const targets = [...optionTargets, ...literalLocations];
95
+ const extra =
96
+ targets.length > 1 ? (targets.find((arg) => arg === "--") ?? targets[1]) : undefined;
97
+
98
+ const unexpected = optionTargets.find((arg) => arg.startsWith("-")) ?? extra;
90
99
  if (unexpected !== undefined) return { error: `unexpected argument ${unexpected}` };
91
100
 
92
101
  const match = /^(.+):(\d+)$/.exec(targets[0] ?? "");
@@ -95,7 +104,7 @@ function parseExplain(args: string[]): ExplainArguments | { error: string } {
95
104
  const line = Number(match[2]);
96
105
  if (line < 1) return { error: `${targets[0]}: the line must be 1 or more` };
97
106
 
98
- return { path: match[1]!, line, noBraces: targets.length < args.length };
107
+ return { path: match[1]!, line, noBraces: noBracesCount > 0 };
99
108
  }
100
109
 
101
110
  function bracesFlag(given: (flag: string) => boolean): Arguments["braces"] {
@@ -293,7 +302,7 @@ function status(
293
302
  return formatted.findings.length > 0 ? 1 : 0;
294
303
  }
295
304
 
296
- function runFiles(args: Arguments, io: Io): number {
305
+ function runFiles(args: Arguments, io: Io): number | Promise<number> {
297
306
  const { cwd } = io;
298
307
 
299
308
  let changed: ReturnType<typeof collectChanged> | undefined;
@@ -336,22 +345,34 @@ function runFiles(args: Arguments, io: Io): number {
336
345
  const run = { cwd, mode: args.mode, braces: args.braces, write: true };
337
346
  const { workerCount, formatPooled } = require("./pool.ts") as typeof import("./pool.ts");
338
347
  const count = workerCount(inputs.length, io.env);
339
- const pooled = count > 0 ? formatPooled(inputs, run, count) : undefined;
340
- const result =
341
- pooled?.formatted ??
342
- formatInputs(
343
- inputs.map((input) => ({ ...input, read: () => readText(input.path) })),
344
- run,
348
+ if (count > 0)
349
+ return formatPooled(inputs, run, count).then(({ formatted, errors }) =>
350
+ finishFiles(args, io, collected.errors, formatted, errors),
345
351
  );
346
352
 
347
- for (const error of pooled?.errors ?? []) warn(io, `stanza: ${error}`);
353
+ const formatted = formatInputs(
354
+ inputs.map((input) => ({ ...input, read: () => readText(input.path) })),
355
+ run,
356
+ );
357
+
358
+ return finishFiles(args, io, collected.errors, formatted, []);
359
+ }
360
+
361
+ function finishFiles(
362
+ args: Arguments,
363
+ io: Io,
364
+ selectionErrors: readonly string[],
365
+ result: Formatted,
366
+ poolErrors: readonly string[],
367
+ ): number {
368
+ for (const error of poolErrors) warn(io, `stanza: ${error}`);
348
369
 
349
370
  printFindings(result.findings, args.json, (line) => io.stdout(`${line}\n`));
350
371
 
351
- for (const error of collected.errors) warn(io, `stanza: ${error}`);
372
+ for (const error of selectionErrors) warn(io, `stanza: ${error}`);
352
373
 
353
- warnUnread(io, cwd, result.unread, result.unreadWidth);
354
- return status([...collected.errors, ...(pooled?.errors ?? [])], result);
374
+ warnUnread(io, io.cwd, result.unread, result.unreadWidth);
375
+ return status([...selectionErrors, ...poolErrors], result);
355
376
  }
356
377
 
357
378
  function shellWord(word: string): string {
@@ -625,7 +646,7 @@ export function runHookCall(call: HookCall, args: string[], io: Io): number {
625
646
  return runStopHook(call, args, io);
626
647
  }
627
648
 
628
- export function main(argv: string[], io: Io): number {
649
+ export function main(argv: string[], io: Io): number | Promise<number> {
629
650
  if (argv[0] === "hook") return runHook(argv.slice(1), io);
630
651
 
631
652
  beginInvocation();
@@ -656,4 +677,8 @@ export function main(argv: string[], io: Io): number {
656
677
  return runFiles(args, io);
657
678
  }
658
679
 
659
- if (import.meta.main) process.exitCode = main(process.argv.slice(2), systemIo());
680
+ // A bytecode build rejects top level await in this module, which the compiled binary bundles.
681
+ if (import.meta.main)
682
+ void Promise.resolve(main(process.argv.slice(2), systemIo())).then((code) => {
683
+ process.exitCode = code;
684
+ });
package/src/depth.ts CHANGED
@@ -366,3 +366,7 @@ export function deepRisk(text: string, jsx: boolean): boolean {
366
366
 
367
367
  return false;
368
368
  }
369
+
370
+ export function tooDeep(path: string, text: string): boolean {
371
+ return deepRisk(text, !/\.[cm]?ts$/.test(path));
372
+ }
@@ -290,9 +290,14 @@ export function explainer(
290
290
  gapsAt.set(start, [...(gapsAt.get(start) ?? []), [list, gap]]);
291
291
  }
292
292
 
293
+ const lineCount =
294
+ original.lines.at(-1) === "" ? original.lines.length - 1 : original.lines.length;
295
+
293
296
  return (line: number): Explanation => {
294
- if (line > original.lines.length)
295
- return { error: `${request.display(path)} has ${original.lines.length} lines, not ${line}` };
297
+ if (line > lineCount)
298
+ return {
299
+ error: `${request.display(path)} has ${lineCount} ${lineCount === 1 ? "line" : "lines"}, not ${line}`,
300
+ };
296
301
 
297
302
  const sections = (gapsAt.get(line) ?? []).map(([list, gap]) => explainGap(traced, list, gap));
298
303
  for (const block of traced.first.braces?.opening(line) ?? [])
@@ -189,20 +189,25 @@ export function blockSpacing(doc: Doc, gap: Gap): Finding[] {
189
189
  return [finding(doc, next.start, "block-spacing")];
190
190
  }
191
191
 
192
+ function fixKeepsBlank(gap: Gap, underComment = gap.next.detached): boolean {
193
+ return gap.decision.want !== "none" || underComment;
194
+ }
195
+
196
+ function commentAbove(doc: Doc, stmt: Stmt): boolean {
197
+ return stmt.detached || lineAt(doc, stmt.start) > stmt.startLine;
198
+ }
199
+
192
200
  function gapEdits(doc: Doc, gap: Gap, edits: LineEdits): Finding[] {
193
201
  const { prev, next, blank, decision } = gap;
194
- if (
195
- decision.want === "keep" ||
196
- decision.want === "frozen" ||
197
- next.detached ||
198
- next.startLine <= prev.endLine ||
199
- (decision.want === "none" ? blank === 0 : blank > 0)
200
- )
201
- return [];
202
+ if (decision.want === "keep" || decision.want === "frozen") return [];
202
203
 
203
- if (decision.want === "none")
204
+ if (decision.want === "none") {
205
+ if (blank === 0 || fixKeepsBlank(gap)) return [];
204
206
  for (const line of blankLines(doc, prev.endLine, next.startLine)) edits.deleteLines.add(line);
205
- else edits.insertAfter.add(next.startLine - 1);
207
+ } else {
208
+ if (blank > 0 || next.startLine <= prev.endLine) return [];
209
+ edits.insertAfter.add(next.startLine - 1);
210
+ }
206
211
 
207
212
  if ("name" in decision)
208
213
  return [finding(doc, next.start, decision.rule, decision.name, decision.reader)];
@@ -252,6 +257,12 @@ function edgeEdits(
252
257
  return findings;
253
258
  }
254
259
 
260
+ function separatedAfterFix(gap: Gap, touched: boolean): boolean {
261
+ if (gap.decision.want === "frozen") return true;
262
+ if (!touched) return gap.blank > 0;
263
+ return gap.decision.want === "at-least-one" || (gap.blank > 0 && fixKeepsBlank(gap));
264
+ }
265
+
255
266
  function walls(
256
267
  doc: Doc,
257
268
  list: StatementList,
@@ -270,8 +281,7 @@ function walls(
270
281
  const counted = stmt && !stmt.multiline && stmt.kind !== "import";
271
282
  const forcedJoined =
272
283
  gap &&
273
- gap.decision.want === "none" &&
274
- !gap.next.detached &&
284
+ !fixKeepsBlank(gap, commentAbove(doc, gap.next)) &&
275
285
  (gap.blank === 0 || touches(gap.prev.startLine, gap.next.endLine));
276
286
 
277
287
  if (!counted || !forcedJoined) {
@@ -290,13 +300,7 @@ function walls(
290
300
  for (let index = 0; index <= list.stmts.length; index++) {
291
301
  const stmt = list.stmts[index];
292
302
  const gap = gaps[index - 1];
293
- const separated =
294
- gap &&
295
- (!gap.next.detached && touches(gap.prev.startLine, gap.next.endLine)
296
- ? gap.decision.want === "frozen" ||
297
- gap.decision.want === "at-least-one" ||
298
- (gap.decision.want === "keep" && gap.blank > 0)
299
- : gap.decision.want === "frozen" || gap.blank > 0);
303
+ const separated = gap && separatedAfterFix(gap, touches(gap.prev.startLine, gap.next.endLine));
300
304
 
301
305
  const counted = stmt && !stmt.multiline && stmt.kind !== "import" && !excluded.has(index);
302
306
  if (!counted || separated) {
@@ -91,7 +91,8 @@ export const RULES = {
91
91
  wall: {
92
92
  fixable: false,
93
93
  gap: null,
94
- summary: "six or more consecutive single-line statements with no blank line",
94
+ summary:
95
+ "six or more consecutive single-line statements with no blank line, reported only where a blank line `--fix` keeps can split the run",
95
96
  message: () => "6 or more statements with no blank line between them; separate the steps",
96
97
  },
97
98
  } as const satisfies Record<string, Rule>;
package/src/files.ts CHANGED
@@ -290,7 +290,19 @@ function hasGitMarker(dir: string): boolean {
290
290
  }
291
291
 
292
292
  const locations = invocationMap<string, Location>();
293
- const repositoryConfigs = invocationMap<string, boolean>();
293
+
294
+ interface GitVariable {
295
+ key: string;
296
+ value: string | undefined;
297
+ }
298
+
299
+ interface GitVariables {
300
+ readable: boolean;
301
+ text: string;
302
+ entries: GitVariable[];
303
+ }
304
+
305
+ const gitVariables = invocationMap<string, GitVariables>();
294
306
 
295
307
  const discoveryEnvironment = [
296
308
  "GIT_DIR",
@@ -298,12 +310,17 @@ const discoveryEnvironment = [
298
310
  "GIT_COMMON_DIR",
299
311
  "GIT_OBJECT_DIRECTORY",
300
312
  "GIT_CEILING_DIRECTORIES",
301
- "GIT_DISCOVERY_ACROSS_FILESYSTEM",
302
313
  "GIT_TEST_ASSUME_DIFFERENT_OWNER",
303
314
  ];
304
315
 
305
- function plainConfig(root: string): boolean {
306
- const cached = repositoryConfigs.get(root);
316
+ function parseGitVariable(line: string): GitVariable {
317
+ const separator = line.indexOf("=");
318
+ if (separator === -1) return { key: line, value: undefined };
319
+ return { key: line.slice(0, separator), value: line.slice(separator + 1) };
320
+ }
321
+
322
+ function listGitVariables(root: string): GitVariables {
323
+ const cached = gitVariables.get(root);
307
324
  if (cached !== undefined) return cached;
308
325
 
309
326
  const result = Bun.spawnSync(["git", "-C", root, "var", "-l"], {
@@ -311,21 +328,34 @@ function plainConfig(root: string): boolean {
311
328
  stderr: "pipe",
312
329
  });
313
330
 
314
- const config = new TextDecoder().decode(result.stdout);
315
- const plain =
316
- result.exitCode === 0 &&
317
- result.stderr.length === 0 &&
318
- !/^(?:core\.worktree|extensions\.[^=]*|include(?:if\.[^=]*)?\.path)(?:=|$)/im.test(config) &&
319
- !/^core\.bare(?:=(?!(?:false|no|off|0)$)|$)/im.test(config) &&
320
- !/^core\.repositoryformatversion(?:=(?![01]$)|$)/im.test(config);
331
+ const text = new TextDecoder().decode(result.stdout);
332
+ const variables = {
333
+ readable: result.exitCode === 0 && result.stderr.length === 0,
334
+ text,
335
+ entries: text.replace(/\n$/, "").split("\n").map(parseGitVariable),
336
+ };
321
337
 
322
- repositoryConfigs.set(root, plain);
323
- return plain;
338
+ gitVariables.set(root, variables);
339
+ return variables;
324
340
  }
325
341
 
326
- function plainRepository(worktree: string, marker: string, markerStat: Stats): boolean {
327
- if (lstatSync(worktree).uid !== process.geteuid!() || markerStat.uid !== process.geteuid!())
328
- return false;
342
+ function plainConfig(root: string): boolean {
343
+ const { readable, text } = listGitVariables(root);
344
+ return (
345
+ readable &&
346
+ !/^(?:core\.worktree|extensions\.[^=]*)(?:=|$)/im.test(text) &&
347
+ !/^core\.bare(?:=(?!(?:false|no|off|0)$)|$)/im.test(text) &&
348
+ !/^core\.repositoryformatversion(?:=(?![01]$)|$)/im.test(text)
349
+ );
350
+ }
351
+
352
+ function plainRepository(
353
+ worktree: string,
354
+ marker: string,
355
+ markerStat: Stats,
356
+ user: number,
357
+ ): boolean {
358
+ if (lstatSync(worktree).uid !== user || markerStat.uid !== user) return false;
329
359
 
330
360
  const head = join(marker, "HEAD");
331
361
  if (!lstatSync(head).isFile()) return false;
@@ -353,7 +383,9 @@ function knownRoot(dir: string): string | undefined {
353
383
  try {
354
384
  if (discoveryEnvironment.some((name) => process.env[name] !== undefined)) return undefined;
355
385
  if (Object.keys(process.env).some((name) => name.startsWith("GIT_CONFIG"))) return undefined;
356
- if (typeof process.geteuid !== "function") return undefined;
386
+
387
+ const user = process.geteuid?.();
388
+ if (user === undefined) return undefined;
357
389
 
358
390
  const start = realpathSync(dir);
359
391
  const startStat = statSync(start);
@@ -367,7 +399,9 @@ function knownRoot(dir: string): string | undefined {
367
399
  const marker = join(current, ".git");
368
400
  const entry = lstatSync(marker, { throwIfNoEntry: false });
369
401
  if (entry !== undefined)
370
- return entry.isDirectory() && plainRepository(current, marker, entry) ? current : undefined;
402
+ return entry.isDirectory() && plainRepository(current, marker, entry, user)
403
+ ? current
404
+ : undefined;
371
405
 
372
406
  if (lstatSync(join(current, "HEAD"), { throwIfNoEntry: false }) !== undefined)
373
407
  return undefined;
@@ -386,10 +420,10 @@ function discoverLocation(dir: string): Location {
386
420
  if (!hasGit()) return { kind: "outside" };
387
421
 
388
422
  const known = knownRoot(dir);
389
- if (known !== undefined) return { kind: "repository", root: known.trim() };
423
+ if (known !== undefined) return { kind: "repository", root: known };
390
424
 
391
425
  const result = runGit(dir, ["rev-parse", "--show-toplevel"]);
392
- const root = result.ok ? result.output.trim() : "";
426
+ const root = result.ok ? result.output.replace(/\n$/, "") : "";
393
427
  if (root) return { kind: "repository", root };
394
428
  if (!result.ok && hasGitMarker(dir)) return { kind: "failed", error: result.error };
395
429
  return { kind: "outside" };
@@ -440,6 +474,176 @@ function isSet(value: string | undefined): boolean {
440
474
 
441
475
  type Attributes = { ok: true; values: Map<string, string> } | { ok: false; error: string };
442
476
 
477
+ function sourceMaySetAttributes(path: string, names: string[]): boolean {
478
+ const entry = lstatSync(path, { throwIfNoEntry: false });
479
+ if (entry === undefined) return false;
480
+ if (!entry.isFile()) return true;
481
+
482
+ const text = readFileSync(path, "utf8");
483
+ return text.includes("[attr]") || names.some((name) => text.includes(name));
484
+ }
485
+
486
+ function indexMayHaveAttributes(root: string): boolean {
487
+ const path = join(root, ".git/index");
488
+ const entry = lstatSync(path, { throwIfNoEntry: false });
489
+ if (entry === undefined) return false;
490
+ if (!entry.isFile()) return true;
491
+
492
+ const bytes = readFileSync(path);
493
+ if (bytes.length < 32 || bytes.toString("ascii", 0, 4) !== "DIRC") return true;
494
+
495
+ const version = bytes.readUInt32BE(4);
496
+ if (version !== 2 && version !== 3) return true;
497
+
498
+ let offset = 12;
499
+ const count = bytes.readUInt32BE(8);
500
+ for (let entryIndex = 0; entryIndex < count; entryIndex++) {
501
+ if (offset + 62 > bytes.length - 20) return true;
502
+ if ((bytes.readUInt32BE(offset + 24) & 0o170000) === 0o040000) return true;
503
+
504
+ const extended = (bytes.readUInt16BE(offset + 60) & 0x4000) !== 0;
505
+ if (extended && version !== 3) return true;
506
+
507
+ const start = offset + 62 + (extended ? 2 : 0);
508
+ const end = bytes.indexOf(0, start);
509
+ if (end < start || end >= bytes.length - 20) return true;
510
+
511
+ const name = bytes.toString("utf8", start, end);
512
+ if (name === ".gitattributes" || name.endsWith("/.gitattributes")) return true;
513
+
514
+ offset += Math.ceil((end + 1 - offset) / 8) * 8;
515
+ }
516
+
517
+ while (offset < bytes.length - 20) {
518
+ if (offset + 8 > bytes.length - 20) return true;
519
+ if (bytes.toString("ascii", offset, offset + 4) !== "TREE") return true;
520
+ offset += 8 + bytes.readUInt32BE(offset + 4);
521
+ }
522
+
523
+ return offset !== bytes.length - 20;
524
+ }
525
+
526
+ // git var -l prints GIT_EDITOR, GIT_SEQUENCE_EDITOR and GIT_PAGER raw, so a newline could forge a line.
527
+ const inertGitEnvironment = new Set([
528
+ "GIT_EDITOR",
529
+ "GIT_SEQUENCE_EDITOR",
530
+ "GIT_PAGER",
531
+ "GIT_TERMINAL_PROMPT",
532
+ "GIT_ASKPASS",
533
+ "GIT_SSH",
534
+ "GIT_SSH_COMMAND",
535
+ "GIT_SSH_VARIANT",
536
+ "GIT_AUTHOR_NAME",
537
+ "GIT_AUTHOR_EMAIL",
538
+ "GIT_AUTHOR_DATE",
539
+ "GIT_COMMITTER_NAME",
540
+ "GIT_COMMITTER_EMAIL",
541
+ "GIT_COMMITTER_DATE",
542
+ "GIT_OPTIONAL_LOCKS",
543
+ ]);
544
+
545
+ function environmentMayAffectAttributes(): boolean {
546
+ return Object.entries(process.env).some(
547
+ ([name, value]) =>
548
+ name.startsWith("GIT_") && (!inertGitEnvironment.has(name) || value?.includes("\n") === true),
549
+ );
550
+ }
551
+
552
+ function rebuildablePath(path: string | undefined): path is string {
553
+ return (
554
+ path !== undefined && (path.startsWith("~/") || !path.startsWith("~")) && !path.includes("%(")
555
+ );
556
+ }
557
+
558
+ function normalizeAsText(path: string): string {
559
+ return path
560
+ .split("/")
561
+ .filter((segment, position) => position === 0 || (segment !== "" && segment !== "."))
562
+ .join("/");
563
+ }
564
+
565
+ function defaultGlobalAttributes(): string | undefined {
566
+ const { HOME: home, XDG_CONFIG_HOME: configHome } = process.env;
567
+ if (configHome) return `${configHome}/git/attributes`;
568
+ return home === undefined ? undefined : `${home}/.config/git/attributes`;
569
+ }
570
+
571
+ function expectedGlobalAttributes(configured: (string | undefined)[]): string | undefined {
572
+ if (!configured.every(rebuildablePath)) return undefined;
573
+
574
+ const path = configured.at(-1);
575
+ const home = process.env.HOME;
576
+ if (path === undefined) return defaultGlobalAttributes();
577
+ if (!path.startsWith("~/")) return path;
578
+ return home === undefined ? undefined : `${home}/${path.slice(2)}`;
579
+ }
580
+
581
+ const attributeVariableOrder = ["GIT_ATTR_SYSTEM", "GIT_ATTR_GLOBAL", "GIT_CONFIG_SYSTEM"];
582
+ // Once each, adjacent and in git's order, so neither path value spans or forges a line.
583
+ function attributeVariableValues(entries: GitVariable[]): (string | undefined)[] | undefined {
584
+ const sequence = entries.flatMap((entry, position) =>
585
+ attributeVariableOrder.includes(entry.key) ? [{ ...entry, position }] : [],
586
+ );
587
+
588
+ const start = sequence[0]?.position;
589
+ const exact =
590
+ sequence.length === attributeVariableOrder.length &&
591
+ sequence.every(
592
+ (entry, offset) =>
593
+ entry.key === attributeVariableOrder[offset] && entry.position - offset === start,
594
+ );
595
+
596
+ return exact ? sequence.map((entry) => entry.value) : undefined;
597
+ }
598
+
599
+ function attributeSourcePaths(root: string): string[] | undefined {
600
+ const variables = gitVariables.get(root);
601
+ if (variables === undefined || !variables.readable) return undefined;
602
+
603
+ const { entries } = variables;
604
+ if (entries.some(({ key }) => /^attr\./i.test(key))) return undefined;
605
+
606
+ const [system, global] = attributeVariableValues(entries) ?? [];
607
+ if (system === undefined || global === undefined) return undefined;
608
+
609
+ const configured = entries
610
+ .filter(({ key }) => key.toLowerCase() === "core.attributesfile")
611
+ .map(({ value }) => value);
612
+
613
+ // git var collapses .. as text but check-attr opens the raw path, where a symlink resolves first.
614
+ const expected = expectedGlobalAttributes(configured);
615
+ if (expected === undefined || normalizeAsText(expected) !== global) return undefined;
616
+
617
+ const paths = [system, global];
618
+ return paths.every(isAbsolute) ? paths : undefined;
619
+ }
620
+
621
+ function attributesMayApply(files: string[], root: string, names: string[]): boolean {
622
+ if (environmentMayAffectAttributes()) return true;
623
+
624
+ const sources = attributeSourcePaths(root);
625
+ if (sources === undefined) return true;
626
+
627
+ try {
628
+ if (indexMayHaveAttributes(root)) return true;
629
+
630
+ const paths = new Set([...sources, join(root, ".git/info/attributes")]);
631
+ for (const file of files) {
632
+ if (!within(root, file)) return true;
633
+
634
+ for (let directory = dirname(file); ; directory = dirname(directory)) {
635
+ paths.add(join(directory, ".gitattributes"));
636
+ if (directory === root) break;
637
+ if (!within(root, directory)) return true;
638
+ }
639
+ }
640
+
641
+ return [...paths].some((path) => sourceMaySetAttributes(path, names));
642
+ } catch {
643
+ return true;
644
+ }
645
+ }
646
+
443
647
  function readAttributes(
444
648
  files: string[],
445
649
  root: string,
@@ -447,6 +651,13 @@ function readAttributes(
447
651
  source: "worktree" | "index",
448
652
  ): Attributes {
449
653
  if (files.length === 0) return { ok: true, values: new Map() };
654
+ if (
655
+ source === "worktree" &&
656
+ names.length === 1 &&
657
+ names[0] === "linguist-generated" &&
658
+ !attributesMayApply(files, root, names)
659
+ )
660
+ return { ok: true, values: new Map() };
450
661
 
451
662
  const paths = files.map((file) => `${repositoryPath(root, file)}\0`).join("");
452
663
  const result = runGit(
package/src/hook.ts CHANGED
@@ -62,7 +62,7 @@ export function hookCall(args: string[], io: Io): HookCall | number {
62
62
  return 0;
63
63
  }
64
64
 
65
- const written = writtenFilesInTranscript(text);
65
+ const written = writtenFilesInCodexRollout(text) ?? writtenFilesInTranscript(text);
66
66
  if (written === undefined || ![...written].some(isCandidateFile)) return 0;
67
67
 
68
68
  return { event: "stop", cwd: input.cwd, written };
@@ -109,7 +109,7 @@ export function hookInput(
109
109
  if (event != null && typeof event !== "string")
110
110
  return { error: "hook_event_name must be a string" };
111
111
 
112
- if (event != null && !events.has(event)) return { event: "ignored" };
112
+ if (event != null && !hookEvents.has(event)) return { event: "ignored" };
113
113
 
114
114
  const cwd = "cwd" in input ? input.cwd : undefined;
115
115
  if (cwd != null && typeof cwd !== "string") return { error: "cwd must be a string" };
@@ -124,7 +124,7 @@ export function hookInput(
124
124
  if (event === "PreToolUse") {
125
125
  const toolInput = "tool_input" in input ? input.tool_input : undefined;
126
126
  if (
127
- !("tool_name" in input && input.tool_name === "Write") ||
127
+ !usesTool(input, "PreToolUse") ||
128
128
  !isRecord(toolInput) ||
129
129
  typeof toolInput.file_path !== "string" ||
130
130
  typeof toolInput.content !== "string"
@@ -160,16 +160,31 @@ export function hookInput(
160
160
  : { ...stop, transcriptPath: path };
161
161
  }
162
162
 
163
- const events = new Set(["Stop", "SubagentStop", "PreToolUse", "PostToolUse"]);
163
+ export const hookEvents: ReadonlySet<string> = new Set([
164
+ "Stop",
165
+ "SubagentStop",
166
+ "PreToolUse",
167
+ "PostToolUse",
168
+ ]);
169
+
170
+ export const hookTools: Readonly<Record<"PostToolUse" | "PreToolUse", ReadonlySet<string>>> = {
171
+ PostToolUse: new Set(["Edit", "MultiEdit", "apply_patch"]),
172
+ PreToolUse: new Set(["Write"]),
173
+ };
174
+
175
+ function usesTool(input: Record<string, unknown>, event: keyof typeof hookTools): boolean {
176
+ return typeof input.tool_name === "string" && hookTools[event].has(input.tool_name);
177
+ }
178
+
164
179
  const patchHeader = /^\*\*\* (Add File|Update File|Move to): (.+)$/;
165
180
  const patchApplied = /^Success\. Updated the following files:$/m;
166
181
  function editedPaths(input: Record<string, unknown>): string[] {
167
182
  const toolInput = input.tool_input;
168
- if (!isRecord(toolInput)) return [];
169
- if (input.tool_name === "Edit" || input.tool_name === "MultiEdit")
183
+ if (!isRecord(toolInput) || !usesTool(input, "PostToolUse")) return [];
184
+ if (input.tool_name !== "apply_patch")
170
185
  return typeof toolInput.file_path === "string" ? [toolInput.file_path] : [];
171
186
 
172
- if (input.tool_name !== "apply_patch" || typeof toolInput.command !== "string") return [];
187
+ if (typeof toolInput.command !== "string") return [];
173
188
  if (typeof input.tool_response !== "string" || !patchApplied.test(input.tool_response)) return [];
174
189
 
175
190
  const paths: string[] = [];
package/src/pool.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { availableParallelism } from "node:os";
2
2
  import { statSync } from "node:fs";
3
- import { workerData, type MessagePort } from "node:worker_threads";
3
+ import type { MessagePort } from "node:worker_threads";
4
4
  import {
5
5
  formatFile,
6
6
  mergeOutcomes,
@@ -10,7 +10,6 @@ import {
10
10
  type Formatted,
11
11
  type Input,
12
12
  } from "./format.ts";
13
- import { deepRisk } from "./depth.ts";
14
13
  import {
15
14
  deserializerFiles,
16
15
  embedDeserializers,
@@ -21,6 +20,11 @@ export const THRESHOLD = 256;
21
20
  export const DEFAULT_WORKERS = 3;
22
21
  export const CHUNK_SIZE = 64;
23
22
 
23
+ export const LANE = { starting: 0, serving: 1, finished: 2, gone: 3 } as const;
24
+ type LaneState = (typeof LANE)[keyof typeof LANE];
25
+
26
+ export type Deferral = (path: string, text: string) => boolean;
27
+
24
28
  export interface FileInput extends Omit<Input, "read"> {
25
29
  output: string;
26
30
  }
@@ -33,7 +37,8 @@ export interface PoolData<Input, Job> {
33
37
  counter: SharedArrayBuffer;
34
38
  signal: SharedArrayBuffer;
35
39
  claims: SharedArrayBuffer;
36
- finished: SharedArrayBuffer;
40
+ lanes: SharedArrayBuffer;
41
+ posted: SharedArrayBuffer;
37
42
  port: MessagePort;
38
43
  addon: string | undefined;
39
44
  deserializers: DeserializerFiles;
@@ -52,10 +57,37 @@ export interface PoolTask<Input, Outcome, Result extends { outcomes: (Outcome |
52
57
  item(input: Input): Outcome;
53
58
  }
54
59
 
60
+ interface Board {
61
+ counter: Int32Array;
62
+ signal: Int32Array;
63
+ claims: Int32Array;
64
+ lanes: Int32Array;
65
+ posted: Int32Array;
66
+ }
67
+
68
+ interface Ledger<Outcome> {
69
+ readonly inputCount: number;
70
+ readonly chunkSize: number;
71
+ readonly results: ((Outcome | null)[] | undefined)[];
72
+ readonly errors: string[];
73
+ pending: number;
74
+ unowned: number;
75
+ }
76
+
77
+ interface Lane {
78
+ readonly port: MessagePort;
79
+ drained: number;
80
+ started: boolean;
81
+ fault: string | undefined;
82
+ exitCode: number | undefined;
83
+ recovered: number;
84
+ }
85
+
55
86
  export function workerCount(
56
87
  fileCount: number,
57
88
  env: Readonly<Record<string, string | undefined>>,
58
89
  maximum = DEFAULT_WORKERS,
90
+ cores = availableParallelism(),
59
91
  ): number {
60
92
  const override = env.STANZA_WORKERS;
61
93
  if (override !== undefined && /^\d+$/.test(override)) {
@@ -65,7 +97,7 @@ export function workerCount(
65
97
 
66
98
  if (fileCount < THRESHOLD) return 0;
67
99
 
68
- return Math.max(0, Math.min(maximum, availableParallelism() - 1));
100
+ return Math.max(0, Math.min(maximum, cores - 1));
69
101
  }
70
102
 
71
103
  export function hardLinked(input: FileInput, run: FormatRun): boolean {
@@ -78,17 +110,13 @@ export function hardLinked(input: FileInput, run: FormatRun): boolean {
78
110
  }
79
111
  }
80
112
 
81
- export function tooDeep(path: string, text: string): boolean {
82
- return deepRisk(text, !/\.[cm]?ts$/.test(path));
83
- }
84
-
85
- export function formatChunk(inputs: FileInput[], run: FormatRun, inWorker: boolean) {
113
+ export function formatChunk(inputs: FileInput[], run: FormatRun, defer?: Deferral) {
86
114
  const warnings = { unread: new Set<string>(), unreadWidth: new Set<string>() };
87
115
  const outcomes = inputs.map((input) => {
88
116
  if (hardLinked(input, run)) return null;
89
117
 
90
118
  const text = readText(input.path);
91
- if (inWorker && typeof text === "string" && tooDeep(input.path, text)) return null;
119
+ if (defer !== undefined && typeof text === "string" && defer(input.path, text)) return null;
92
120
 
93
121
  return formatFile({ ...input, read: () => text }, run, input.output, warnings);
94
122
  });
@@ -96,159 +124,293 @@ export function formatChunk(inputs: FileInput[], run: FormatRun, inWorker: boole
96
124
  return { outcomes, unread: [...warnings.unread], unreadWidth: [...warnings.unreadWidth] };
97
125
  }
98
126
 
99
- function acceptChunk<Input, Outcome, Result extends { outcomes: (Outcome | null)[] }, Job>(
100
- inputCount: number,
101
- chunkSize: number,
127
+ function wake(signal: Int32Array): void {
128
+ Atomics.add(signal, 0, 1);
129
+ Atomics.notify(signal, 0);
130
+ }
131
+
132
+ function errorText(error: unknown): string {
133
+ return error instanceof Error ? error.message : String(error);
134
+ }
135
+
136
+ function chunkLength(ledger: Ledger<unknown>, chunk: number): number {
137
+ return Math.min(ledger.chunkSize, ledger.inputCount - chunk * ledger.chunkSize);
138
+ }
139
+
140
+ function settle<Outcome>(
141
+ ledger: Ledger<Outcome>,
142
+ chunk: number,
143
+ outcomes: (Outcome | null)[],
144
+ ): boolean {
145
+ if (ledger.results[chunk] !== undefined) return false;
146
+
147
+ ledger.results[chunk] = outcomes;
148
+ ledger.pending--;
149
+ return true;
150
+ }
151
+
152
+ function settleOnMain(ledger: Ledger<unknown>, chunk: number): boolean {
153
+ return settle(ledger, chunk, Array<null>(chunkLength(ledger, chunk)).fill(null));
154
+ }
155
+
156
+ function accept<Input, Outcome, Result extends { outcomes: (Outcome | null)[] }, Job>(
157
+ ledger: Ledger<Outcome>,
102
158
  message: ChunkMessage<Result>,
103
- chunks: (Outcome | null)[][],
104
159
  task: PoolTask<Input, Outcome, Result, Job>,
105
- errors: string[],
106
160
  ): void {
107
161
  if ("error" in message) {
108
- errors.push(message.error);
109
- if (message.chunk === undefined) return;
162
+ if (message.chunk === undefined || settleOnMain(ledger, message.chunk))
163
+ ledger.errors.push(message.error);
110
164
 
111
- const size = Math.min(chunkSize, inputCount - message.chunk * chunkSize);
112
- chunks[message.chunk] = Array<null>(size).fill(null);
113
165
  return;
114
166
  }
115
167
 
116
- chunks[message.chunk] = message.outcomes;
117
- task.merge(message);
168
+ if (settle(ledger, message.chunk, message.outcomes)) task.merge(message);
169
+ }
170
+
171
+ function stopped(states: LaneState[]): boolean {
172
+ return states.every((state) => state >= LANE.finished);
173
+ }
174
+
175
+ function quiet(
176
+ index: number,
177
+ states: LaneState[],
178
+ posted: number[],
179
+ lanes: Map<number, Lane>,
180
+ ): boolean {
181
+ return states[index]! >= LANE.finished && (lanes.get(index)?.drained ?? 0) >= posted[index]!;
118
182
  }
119
183
 
120
- function recoverAbandoned<Outcome>(
121
- inputCount: number,
122
- chunkSize: number,
123
- chunks: (Outcome | null)[][],
184
+ function recoverStopped(
185
+ ledger: Ledger<unknown>,
124
186
  claims: Int32Array,
125
- stopped: boolean[],
126
- errors: string[],
127
- ): number {
128
- let recovered = 0;
187
+ states: LaneState[],
188
+ posted: number[],
189
+ lanes: Map<number, Lane>,
190
+ ): void {
191
+ const everyLaneQuiet = states.every((_, index) => quiet(index, states, posted, lanes));
129
192
  for (let chunk = 0; chunk < claims.length; chunk++) {
130
193
  const owner = Atomics.load(claims, chunk);
131
- if (chunks[chunk] !== undefined || owner === 0 || !stopped[owner - 1]) continue;
194
+ const ownerQuiet = owner !== 0 && quiet(owner - 1, states, posted, lanes);
195
+ if (!ownerQuiet && !everyLaneQuiet) continue;
196
+ if (!settleOnMain(ledger, chunk)) continue;
132
197
 
133
- const size = Math.min(chunkSize, inputCount - chunk * chunkSize);
134
- chunks[chunk] = Array<null>(size).fill(null);
135
- errors.push("a worker thread stopped before reporting its files, so main formatted them");
136
- recovered++;
198
+ const lane = lanes.get(owner - 1);
199
+ if (lane === undefined) ledger.unowned += chunkLength(ledger, chunk);
200
+ else lane.recovered += chunkLength(ledger, chunk);
137
201
  }
202
+ }
203
+
204
+ function fileCount(count: number): string {
205
+ return `${count} ${count === 1 ? "file" : "files"}`;
206
+ }
207
+
208
+ function laneLoss(lane: Lane): string | undefined {
209
+ const exit = `exited with code ${lane.exitCode}`;
210
+ if (!lane.started)
211
+ return `a worker thread failed to start, so main did its share: ${lane.fault ?? exit}`;
212
+
213
+ if (lane.recovered === 0 && lane.fault === undefined && (lane.exitCode ?? 0) !== 0)
214
+ return `a worker thread ${exit}, so main did its share`;
215
+
216
+ if (lane.recovered === 0) return lane.fault;
138
217
 
139
- return recovered;
218
+ const files = fileCount(lane.recovered);
219
+ if (lane.fault !== undefined)
220
+ return `a worker thread failed before reporting ${files}, so main took them over: ${lane.fault}`;
221
+
222
+ const ending = lane.exitCode === undefined ? "stopped" : exit;
223
+ return `a worker thread ${ending} before reporting ${files}, so main took them over`;
224
+ }
225
+
226
+ function recoveredAny(ledger: Ledger<unknown>, lanes: Map<number, Lane>): boolean {
227
+ return ledger.unowned > 0 || [...lanes.values()].some((lane) => lane.recovered > 0);
140
228
  }
141
229
 
142
- export function runPooled<Input, Outcome, Result extends { outcomes: (Outcome | null)[] }, Job>(
230
+ function losses(ledger: Ledger<unknown>, lanes: Map<number, Lane>): string[] {
231
+ const laneLosses = [...lanes.values()].flatMap((lane) => laneLoss(lane) ?? []);
232
+ const unowned =
233
+ ledger.unowned === 0
234
+ ? []
235
+ : [
236
+ `a worker thread stopped before reporting ${fileCount(ledger.unowned)}, so main took them over`,
237
+ ];
238
+
239
+ return [...ledger.errors, ...laneLosses, ...unowned];
240
+ }
241
+
242
+ export async function runPooled<
243
+ Input,
244
+ Outcome,
245
+ Result extends { outcomes: (Outcome | null)[] },
246
+ Job,
247
+ >(
143
248
  inputs: Input[],
144
249
  task: PoolTask<Input, Outcome, Result, Job>,
145
250
  count: number,
146
- ): { outcomes: Outcome[]; errors: string[] } {
251
+ ): Promise<{ outcomes: Outcome[]; errors: string[] }> {
147
252
  const { Worker, MessageChannel, receiveMessageOnPort } =
148
253
  require("node:worker_threads") as typeof import("node:worker_threads");
149
254
 
150
- const counter = new Int32Array(new SharedArrayBuffer(4));
151
- const signal = new Int32Array(new SharedArrayBuffer(4));
152
-
153
255
  const chunkSize = task.chunkSize ?? CHUNK_SIZE;
154
256
  const chunkCount = Math.ceil(inputs.length / chunkSize);
155
- const claims = new Int32Array(new SharedArrayBuffer(4 * chunkCount));
156
- const finished = new Int32Array(new SharedArrayBuffer(4 * Math.max(count, 1)));
157
- const chunks: (Outcome | null)[][] = Array(chunkCount);
158
-
159
- const errors: string[] = [];
160
- const ports: MessagePort[] = [];
257
+ const board: Board = {
258
+ counter: new Int32Array(new SharedArrayBuffer(4)),
259
+ signal: new Int32Array(new SharedArrayBuffer(4)),
260
+ claims: new Int32Array(new SharedArrayBuffer(4 * chunkCount)),
261
+ lanes: new Int32Array(new SharedArrayBuffer(4 * count)),
262
+ posted: new Int32Array(new SharedArrayBuffer(4 * count)),
263
+ };
264
+
265
+ const ledger: Ledger<Outcome> = {
266
+ inputCount: inputs.length,
267
+ chunkSize,
268
+ results: Array.from({ length: chunkCount }, () => undefined),
269
+ errors: [],
270
+ pending: chunkCount,
271
+ unowned: 0,
272
+ };
273
+
274
+ const lanes = new Map<number, Lane>();
161
275
  const deserializers = deserializerFiles();
162
- for (let index = 0; index < count; index++) {
276
+ let open = true;
277
+
278
+ for (let id = 0; id < count; id++) {
163
279
  const { port1, port2 } = new MessageChannel();
164
280
  try {
165
281
  const workerData: PoolData<Input, Job> = {
166
- id: index,
282
+ id,
167
283
  inputs,
168
284
  job: task.job,
169
285
  chunkSize,
170
- counter: counter.buffer as SharedArrayBuffer,
171
- signal: signal.buffer as SharedArrayBuffer,
172
- claims: claims.buffer as SharedArrayBuffer,
173
- finished: finished.buffer as SharedArrayBuffer,
286
+ counter: board.counter.buffer as SharedArrayBuffer,
287
+ signal: board.signal.buffer as SharedArrayBuffer,
288
+ claims: board.claims.buffer as SharedArrayBuffer,
289
+ lanes: board.lanes.buffer as SharedArrayBuffer,
290
+ posted: board.posted.buffer as SharedArrayBuffer,
174
291
  port: port2,
175
292
  addon: process.env.NAPI_RS_NATIVE_LIBRARY_PATH,
176
293
  deserializers,
177
294
  };
178
295
 
179
296
  const worker = new Worker(task.worker, { workerData, transferList: [port2] });
180
- worker.on("error", (error: Error) => errors.push(error.message));
297
+ const lane: Lane = {
298
+ port: port1,
299
+ drained: 0,
300
+ started: true,
301
+ fault: undefined,
302
+ exitCode: undefined,
303
+ recovered: 0,
304
+ };
305
+
306
+ worker.on("error", (error: Error) => {
307
+ if (!open) return;
308
+ lane.fault ??= error.message;
309
+ wake(board.signal);
310
+ });
311
+
312
+ worker.on("exit", (code: number) => {
313
+ if (!open) return;
314
+
315
+ lane.started = Atomics.load(board.lanes, id) !== LANE.starting;
316
+ lane.exitCode = code;
317
+ Atomics.store(board.lanes, id, LANE.gone);
318
+ wake(board.signal);
319
+ });
320
+
181
321
  worker.unref();
182
- ports.push(port1);
322
+ lanes.set(id, lane);
183
323
  } catch (error: unknown) {
184
- errors.push(error instanceof Error ? error.message : String(error));
324
+ Atomics.store(board.lanes, id, LANE.gone);
325
+ ledger.errors.push(errorText(error));
185
326
  port1.close();
186
327
  port2.close();
187
328
  }
188
329
  }
189
330
 
190
- let completed = 0;
191
- while (completed < chunkCount) {
192
- const observed = Atomics.load(signal, 0);
193
- const stopped = Array.from(finished, (_, index) => Atomics.load(finished, index) === 1);
194
-
195
- for (const port of ports) {
196
- let received: ReturnType<typeof receiveMessageOnPort>;
197
- while ((received = receiveMessageOnPort(port)) !== undefined) {
198
- const message = received.message as ChunkMessage<Result>;
199
- acceptChunk(inputs.length, chunkSize, message, chunks, task, errors);
200
- if (message.chunk !== undefined) completed++;
331
+ try {
332
+ for (;;) {
333
+ const observed = Atomics.load(board.signal, 0);
334
+ const states = Array.from(
335
+ board.lanes,
336
+ (_, index) => Atomics.load(board.lanes, index) as LaneState,
337
+ );
338
+
339
+ const posted = Array.from(board.posted, (_, index) => Atomics.load(board.posted, index));
340
+
341
+ for (const lane of lanes.values()) {
342
+ let received: ReturnType<typeof receiveMessageOnPort>;
343
+ while ((received = receiveMessageOnPort(lane.port)) !== undefined) {
344
+ lane.drained++;
345
+ accept(ledger, received.message as ChunkMessage<Result>, task);
346
+ }
201
347
  }
202
- }
203
348
 
204
- const chunk = Atomics.add(counter, 0, 1);
205
- if (chunk < chunkCount) {
206
- try {
207
- const result = task.chunk(inputs.slice(chunk * chunkSize, (chunk + 1) * chunkSize));
208
- acceptChunk(inputs.length, chunkSize, { chunk, ...result }, chunks, task, errors);
209
- } catch (error: unknown) {
210
- acceptChunk(
211
- inputs.length,
212
- chunkSize,
213
- { chunk, error: error instanceof Error ? error.message : String(error) },
214
- chunks,
215
- task,
216
- errors,
217
- );
349
+ const chunk =
350
+ Atomics.load(board.counter, 0) < chunkCount ? Atomics.add(board.counter, 0, 1) : chunkCount;
351
+
352
+ if (chunk < chunkCount) {
353
+ try {
354
+ const result = task.chunk(inputs.slice(chunk * chunkSize, (chunk + 1) * chunkSize));
355
+ accept(ledger, { chunk, ...result }, task);
356
+ } catch (error: unknown) {
357
+ accept(ledger, { chunk, error: errorText(error) }, task);
358
+ }
359
+
360
+ continue;
218
361
  }
219
362
 
220
- completed++;
221
- continue;
222
- }
363
+ recoverStopped(ledger, board.claims, states, posted, lanes);
223
364
 
224
- completed += recoverAbandoned(inputs.length, chunkSize, chunks, claims, stopped, errors);
225
- if (completed < chunkCount) Atomics.wait(signal, 0, observed, 50);
226
- }
365
+ const undelivered = [...lanes].some(([index, lane]) => lane.drained < posted[index]!);
366
+ const exited = [...lanes.values()].every((lane) => lane.exitCode !== undefined);
367
+ const settled = ledger.pending === 0 && stopped(states) && !undelivered;
368
+ if (settled && (exited || !recoveredAny(ledger, lanes))) break;
227
369
 
228
- const outcomes: Outcome[] = [];
229
- for (let chunk = 0; chunk < chunks.length; chunk++)
230
- for (const [offset, outcome] of chunks[chunk]!.entries()) {
231
- const input = inputs[chunk * chunkSize + offset]!;
232
- outcomes.push(outcome ?? task.item(input));
370
+ if (undelivered && stopped(states)) {
371
+ await new Promise((resolve) => setImmediate(resolve));
372
+ continue;
373
+ }
374
+
375
+ // Bun releases a waitAsync's hold on the event loop when another thread notifies, before main resumes.
376
+ const holdLoop = setInterval(() => {}, 2 ** 30);
377
+ try {
378
+ await Atomics.waitAsync(board.signal, 0, observed).value;
379
+ } finally {
380
+ clearInterval(holdLoop);
381
+ }
233
382
  }
383
+ } finally {
384
+ open = false;
385
+ for (const lane of lanes.values()) lane.port.close();
386
+ }
234
387
 
235
- for (const port of ports) port.close();
388
+ const outcomes: Outcome[] = [];
389
+ for (const [chunk, results] of ledger.results.entries())
390
+ for (const [offset, outcome] of results!.entries())
391
+ outcomes.push(outcome ?? task.item(inputs[chunk * chunkSize + offset]!));
236
392
 
237
- return { outcomes, errors };
393
+ return { outcomes, errors: losses(ledger, lanes) };
238
394
  }
239
395
 
240
396
  export function serveChunks<Input, Job, Result>(work: (inputs: Input[], job: Job) => Result): void {
397
+ const { workerData } = require("node:worker_threads") as typeof import("node:worker_threads");
241
398
  const data = workerData as PoolData<Input, Job>;
399
+
242
400
  const counter = new Int32Array(data.counter);
243
401
  const signal = new Int32Array(data.signal);
244
402
  const claims = new Int32Array(data.claims);
245
- const finished = new Int32Array(data.finished);
403
+ const lanes = new Int32Array(data.lanes);
404
+ const posted = new Int32Array(data.posted);
246
405
  function post(message: ChunkMessage<Result>): void {
247
406
  data.port.postMessage(message);
248
- Atomics.add(signal, 0, 1);
249
- Atomics.notify(signal, 0);
407
+ Atomics.add(posted, data.id, 1);
408
+ wake(signal);
250
409
  }
251
410
 
411
+ Atomics.store(lanes, data.id, LANE.serving);
412
+ wake(signal);
413
+
252
414
  try {
253
415
  if (data.addon !== undefined) process.env.NAPI_RS_NATIVE_LIBRARY_PATH = data.addon;
254
416
  embedDeserializers(data.deserializers);
@@ -269,35 +431,34 @@ export function serveChunks<Input, Job, Result>(work: (inputs: Input[], job: Job
269
431
 
270
432
  post({ chunk, ...result });
271
433
  } catch (error: unknown) {
272
- post({ chunk, error: error instanceof Error ? error.message : String(error) });
434
+ post({ chunk, error: errorText(error) });
273
435
  }
274
436
  }
275
437
  } catch (error: unknown) {
276
- post({ chunk: undefined, error: error instanceof Error ? error.message : String(error) });
438
+ post({ chunk: undefined, error: errorText(error) });
277
439
  } finally {
278
- Atomics.store(finished, data.id, 1);
279
- Atomics.add(signal, 0, 1);
280
- Atomics.notify(signal, 0);
440
+ Atomics.store(lanes, data.id, LANE.finished);
441
+ wake(signal);
281
442
  }
282
443
  }
283
444
 
284
- export function formatPooled(
445
+ export async function formatPooled(
285
446
  inputs: FileInput[],
286
447
  run: FormatRun,
287
448
  count: number,
288
- ): { formatted: Formatted; errors: string[] } {
449
+ ): Promise<{ formatted: Formatted; errors: string[] }> {
289
450
  const warnings = { unread: new Set<string>(), unreadWidth: new Set<string>() };
290
451
  // A compiled Bun worker resolves a bare specifier inside bunfs, not a file URL.
291
452
  const specifier = Bun.main.includes("/$bunfs/")
292
453
  ? "./worker.ts"
293
454
  : new URL("./worker.ts", import.meta.url);
294
455
 
295
- const { outcomes, errors } = runPooled(
456
+ const { outcomes, errors } = await runPooled(
296
457
  inputs,
297
458
  {
298
459
  worker: specifier,
299
460
  job: run,
300
- chunk: (inputs) => formatChunk(inputs, run, false),
461
+ chunk: (inputs) => formatChunk(inputs, run),
301
462
  merge(result) {
302
463
  for (const path of result.unread) warnings.unread.add(path);
303
464
  for (const path of result.unreadWidth) warnings.unreadWidth.add(path);
package/src/usage.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export const bothBraces = "use one of --braces or --no-braces";
2
2
 
3
3
  export const usage =
4
- "Usage: stanza (--fix | --check) [--changed [--hunks] | --stdin <path> | [--] <paths...>] [--json] [--braces | --no-braces]\n stanza --check --staged [--hunks] [--json] [--braces | --no-braces]\n stanza explain <file>:<line> [--no-braces]\n stanza hook [--braces | --no-braces] [--hunks]";
4
+ "Usage: stanza (--fix | --check) [--changed [--hunks] | --stdin <path> | [--] <paths...>] [--json] [--braces | --no-braces]\n stanza --check --staged [--hunks] [--json] [--braces | --no-braces]\n stanza explain [--no-braces] [--] <file>:<line>\n stanza hook [--braces | --no-braces] [--hunks]";
5
5
 
6
6
  export const flags: (readonly [string, string])[] = [
7
7
  ["--fix", "apply every deterministic rule in place"],
@@ -19,7 +19,7 @@ export const flags: (readonly [string, string])[] = [
19
19
  ["explain <file>:<line>", "which rule decides the gap or braced body at that line, and why"],
20
20
  [
21
21
  "hook",
22
- "Stop and SubagentStop; PostToolUse on Edit, MultiEdit and Codex apply_patch; PreToolUse on Write; reads JSON on stdin",
22
+ "Stop and SubagentStop; PostToolUse on Edit, MultiEdit and Codex `apply_patch`; PreToolUse on Write; reads JSON on stdin",
23
23
  ],
24
24
  ["--help", "usage, flags and the rule catalog"],
25
25
  ["--version", "the version, and for a built binary the commit it was built from"],
package/src/worker.ts CHANGED
@@ -1,4 +1,5 @@
1
+ import { tooDeep } from "./depth.ts";
1
2
  import { formatChunk, serveChunks, type FileInput } from "./pool.ts";
2
3
  import type { FormatRun } from "./format.ts";
3
4
 
4
- serveChunks((inputs: FileInput[], run: FormatRun) => formatChunk(inputs, run, true));
5
+ serveChunks((inputs: FileInput[], run: FormatRun) => formatChunk(inputs, run, tooDeep));