@tayomi/deterministic-gates 0.9.0 → 0.10.1

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.
@@ -8,9 +8,20 @@ interface GitOptions {
8
8
  input?: string;
9
9
  }
10
10
 
11
- /** Runs git in the repo, and gives what it printed, trimmed. */
11
+ /**
12
+ * Runs git in the repo, and gives what it printed, without the line break that ends it, however long. Nothing else is
13
+ * trimmed: the name of a file may start with a space.
14
+ */
12
15
  function git(root: string, args: string[], { env = process.env, input }: GitOptions = {}): string {
13
- return execFileSync("git", args, { cwd: root, encoding: "utf8", env, input, stdio: "pipe" }).trim();
16
+ const printed = execFileSync("git", args, {
17
+ cwd: root,
18
+ encoding: "utf8",
19
+ env,
20
+ input,
21
+ stdio: "pipe",
22
+ maxBuffer: Infinity,
23
+ });
24
+ return printed.replace(/\n$/, "");
14
25
  }
15
26
 
16
27
  // One NUL after each path, which git otherwise quotes and escapes when it holds an accent.
@@ -118,3 +129,86 @@ export function fileAt(root: string, commit: string, file: string): string | und
118
129
  export function changedSince(root: string, start: string, end = workingTree(root)): string[] {
119
130
  return paths(git(root, ["diff", "-z", "--name-only", start, end])).sort();
120
131
  }
132
+
133
+ /** A commit, with its parents, and when it was committed, in seconds. */
134
+ export interface Commit {
135
+ hash: string;
136
+ parents: string[];
137
+ at: number;
138
+ }
139
+
140
+ /** The commit HEAD is on, and the tips of the branches: nothing in a repo with no commit. */
141
+ export function branchTips(root: string): { head?: string; tips: string[] } {
142
+ try {
143
+ const head = git(root, ["rev-parse", "--verify", "--quiet", "HEAD"]);
144
+ const tips = git(root, ["for-each-ref", "--format=%(objectname)", "refs/heads"]).split("\n");
145
+ return { head, tips: [...new Set([head, ...tips.filter(Boolean)])] };
146
+ } catch {
147
+ return { tips: [] };
148
+ }
149
+ }
150
+
151
+ /** The folder of git that the worktrees of a repo share: what tells that two of them are of the same repo. */
152
+ export function sharedDir(root: string): string {
153
+ try {
154
+ return git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
155
+ } catch {
156
+ return root;
157
+ }
158
+ }
159
+
160
+ /** Whether a commit is another one, or one it holds. */
161
+ export function isIn(root: string, commit: string, other: string): boolean {
162
+ try {
163
+ git(root, ["merge-base", "--is-ancestor", commit, other]);
164
+ return true;
165
+ } catch {
166
+ return false;
167
+ }
168
+ }
169
+
170
+ /** The commits these tips hold that none of the known commits does. It throws when git no longer has one of them. */
171
+ export function commitsPast(root: string, tips: string[], known: string[]): Commit[] {
172
+ const input = known.map((commit) => `^${commit}\n`).join("");
173
+ // Two lines a commit: "commit", its hash and its parents, then its time.
174
+ const lines = git(root, ["rev-list", "--parents", "--format=%ct", "--stdin", ...tips], { input }).split("\n");
175
+ return lines.filter(Boolean).flatMap((line, at, all) => {
176
+ if (at % 2) return [];
177
+ const [, hash = "", ...parents] = line.split(" ");
178
+ return [{ hash, parents, at: Number(all[at + 1]) }];
179
+ });
180
+ }
181
+
182
+ /** Lines a change wrote in a file: where they start, and how many. None of them, where it only cut lines out after that one. */
183
+ export interface WrittenLines {
184
+ at: number;
185
+ lines: number;
186
+ }
187
+
188
+ /**
189
+ * The lines of a file the working tree wrote since a commit that has the file. The file is compared with the one of
190
+ * the commit, not through the index, which does not know a file nobody added; and with the diff of git itself, plain,
191
+ * whatever colours or program the owner set for it.
192
+ */
193
+ export function writtenSince(root: string, commit: string, file: string): WrittenLines[] {
194
+ const plain = ["--no-color", "--no-ext-diff", "--no-textconv", "--unified=0", "--inter-hunk-context=0"];
195
+ // The name as it is: git would otherwise read the brackets of a file such as [slug].ts as a pattern.
196
+ const diff = git(root, ["--literal-pathspecs", "diff", ...plain, `${commit}:${file}`, "--", file]);
197
+ const hunks = diff.matchAll(/^@@ -\S+ \+(\d+)(?:,(\d+))? @@/gm);
198
+ return [...hunks].map(([, at, lines = "1"]) => ({ at: Number(at), lines: Number(lines) }));
199
+ }
200
+
201
+ // Fewer names at once than a command line holds.
202
+ const NAMES_AT_ONCE = 500;
203
+
204
+ /** The ones of these files a commit has. */
205
+ export function filesAt(root: string, commit: string, files: string[]): string[] {
206
+ const found: string[] = [];
207
+ for (let at = 0; at < files.length; at += NAMES_AT_ONCE) {
208
+ const names = files.slice(at, at + NAMES_AT_ONCE);
209
+ found.push(
210
+ ...paths(git(root, ["--literal-pathspecs", "ls-tree", "-r", "--name-only", "-z", commit, "--", ...names])),
211
+ );
212
+ }
213
+ return found;
214
+ }
@@ -2,6 +2,7 @@ import { writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import type { GatesFiles } from "./config.ts";
5
+ import type { Head, There } from "./head.ts";
5
6
  import { isRecord, isStringArray, isStringRecord, readJsonFile } from "./json.ts";
6
7
 
7
8
  /** A red gate the agent chose to leave, with why, bound to the fingerprint of the report it saw. */
@@ -21,11 +22,11 @@ export interface SendBacks {
21
22
  }
22
23
 
23
24
  /**
24
- * What a turn started from: the commit, the reports of its compared gates, and the gates files themselves, since a
25
- * turn is checked with the gates it started with. A turn the owner interrupts never reaches its check: it stays
26
- * unchecked until the next turn of its repo. Once checked, what its stops told the agent.
25
+ * What a turn started from: the commit, where HEAD was, the reports of its compared gates, and the gates files
26
+ * themselves, since a turn is checked with the gates it started with. A turn the owner interrupts never reaches its
27
+ * check: it stays unchecked until the next turn of its repo. Once checked, what its stops told the agent.
27
28
  */
28
- export interface TurnState {
29
+ export interface TurnState extends Head {
29
30
  start: string;
30
31
  baselines: Record<string, string>;
31
32
  config: GatesFiles;
@@ -52,6 +53,8 @@ interface SessionState {
52
53
  told?: Record<string, string[]>;
53
54
  /** The repos a send-back of the session told the agent how to act in: the next ones there say it in one line. */
54
55
  conductTold?: string[];
56
+ /** What the session knows of the commits of each repo, for as long as it lasts, whatever repo its turns are in. */
57
+ there?: Record<string, There>;
55
58
  }
56
59
 
57
60
  const EMPTY: SessionState = { turns: {} };
@@ -78,6 +81,8 @@ function isTurnState(value: unknown): value is TurnState {
78
81
  return (
79
82
  isRecord(value) &&
80
83
  typeof value.start === "string" &&
84
+ (value.head === undefined || typeof value.head === "string") &&
85
+ (value.at === undefined || typeof value.at === "number") &&
81
86
  isStringRecord(value.baselines) &&
82
87
  isGatesFiles(value.config) &&
83
88
  typeof value.checked === "boolean" &&
@@ -85,6 +90,10 @@ function isTurnState(value: unknown): value is TurnState {
85
90
  );
86
91
  }
87
92
 
93
+ function isThere(value: unknown): value is There {
94
+ return isRecord(value) && isStringArray(value.known) && isStringArray(value.made);
95
+ }
96
+
88
97
  function isSessionState(value: unknown): value is SessionState {
89
98
  return (
90
99
  isRecord(value) &&
@@ -92,7 +101,8 @@ function isSessionState(value: unknown): value is SessionState {
92
101
  isRecord(value.turns) &&
93
102
  Object.values(value.turns).every(isTurnState) &&
94
103
  (value.told === undefined || (isRecord(value.told) && Object.values(value.told).every(isStringArray))) &&
95
- (value.conductTold === undefined || isStringArray(value.conductTold))
104
+ (value.conductTold === undefined || isStringArray(value.conductTold)) &&
105
+ (value.there === undefined || (isRecord(value.there) && Object.values(value.there).every(isThere)))
96
106
  );
97
107
  }
98
108
 
@@ -120,6 +130,16 @@ export function writeTurn(session: string, root: string, turn: TurnState): void
120
130
  writeSession(session, { ...state, current: root, turns: { ...Object.fromEntries(unchecked), [root]: turn } });
121
131
  }
122
132
 
133
+ /** What the session knows of the commits of a repo, or nothing before its first turn there. */
134
+ export function readThere(session: string, root: string): There | undefined {
135
+ return readSession(session).there?.[root];
136
+ }
137
+
138
+ export function writeThere(session: string, root: string, there: There): void {
139
+ const state = readSession(session);
140
+ writeSession(session, { ...state, there: { ...state.there, [root]: there } });
141
+ }
142
+
123
143
  /** Ends the turn in progress without a check, as a prompt from a folder with no gates, or a failed start, does. */
124
144
  export function forgetTurn(session: string): void {
125
145
  forget(session, "current");
package/src/core/watch.ts CHANGED
@@ -398,6 +398,7 @@ export async function judgeWatch(
398
398
  gate: WatchedGate,
399
399
  files: string[],
400
400
  baseline: string | undefined,
401
+ elsewhere = false,
401
402
  ): Promise<Outcome> {
402
403
  const folder = folderOf(root, gate);
403
404
  const owed = owedFiles(folder);
@@ -413,7 +414,7 @@ export async function judgeWatch(
413
414
  }
414
415
  // Paid, less what a stop out of time meanwhile added: only the lists this stop asked for.
415
416
  for (const list of owed.lists) rmSync(list, { force: true });
416
- const judged = judgeCycle(gate, settled.cycle, baseline, asked);
417
+ const judged = judgeCycle(gate, settled.cycle, baseline, asked, elsewhere);
417
418
  return { name, ms, ...judged, report: judged.ok ? settled.cycle : undefined };
418
419
  }
419
420
 
@@ -423,10 +424,11 @@ function judgeCycle(
423
424
  cycle: string,
424
425
  baseline: string | undefined,
425
426
  files: string[],
427
+ elsewhere: boolean,
426
428
  ): { ok: boolean; output: string } {
427
429
  const fails = new RegExp(gate.watch.failed ?? "(?!)");
428
430
  return isCompared(gate)
429
- ? addedLines(gate, cycle, baseline, files)
431
+ ? addedLines(gate, cycle, baseline, files, elsewhere)
430
432
  : { ok: !cycle.split("\n").some((line) => fails.test(line)), output: cycle };
431
433
  }
432
434
 
@@ -58,22 +58,27 @@ export function newBulkSuppressions(
58
58
  );
59
59
  }
60
60
 
61
- function main(root: string, turn: string, files: string[]): void {
62
- const found = files.flatMap((file) => {
61
+ /** The counts the turn raised in the suppressions files given, each under the name of its file. */
62
+ export function bulkSuppressions(root: string, turn: string, files: string[]): string[] {
63
+ return files.flatMap((file) => {
63
64
  const before = fileAt(root, turn, file);
64
- // ESLint names a source from the folder it runs in, which holds its suppressions file unless the repo moved it:
65
- // a source not found there is never taken for a moved one.
66
- const moved = (source: string) => {
67
- const path = join(dirname(file), source);
68
- return existsSync(join(root, path)) && fileAt(root, turn, path) === undefined;
69
- };
65
+ // ESLint names a source from the folder it runs in: the one of its suppressions file, or the root of the repo
66
+ // when the repo keeps that file in a folder of its own. A source found in neither is never taken for a moved one.
67
+ const moved = (source: string) =>
68
+ [join(dirname(file), source), source].some(
69
+ (path) => existsSync(join(root, path)) && fileAt(root, turn, path) === undefined,
70
+ );
70
71
  const rose = newBulkSuppressions(
71
72
  before === undefined ? undefined : parseJson(before),
72
- parseJson(readFileSync(file, "utf8")),
73
+ parseJson(readFileSync(join(root, file), "utf8")),
73
74
  moved,
74
75
  );
75
76
  return rose.map((line) => `${file}: ${line}`);
76
77
  });
78
+ }
79
+
80
+ function main(root: string, turn: string, files: string[]): void {
81
+ const found = bulkSuppressions(root, turn, files);
77
82
  if (!found.length) return;
78
83
  console.log(headed("New bulk suppressions: fix the violations, never the file that hides them.", found));
79
84
  process.exitCode = 1;
@@ -1,33 +1,112 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { mkdtempSync, rmSync } from "node:fs";
2
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { isRecord, readJsonFile } from "../core/json.ts";
6
6
  import { headed, packageScript } from "../core/run.ts";
7
+ import { filesAt, type WrittenLines, writtenSince } from "../core/snapshot.ts";
7
8
 
8
9
  // jscpd compared with the tree the turn started from. Its own console report lists every clone of the repo, the old
9
10
  // ones included, so this prints only the clones the turn added, one per line.
11
+ //
12
+ // jscpd tells a clone by its two files and where it stands in them, so it also calls new an old clone the turn only
13
+ // disturbed: two old files it pairs once the turn takes their copy out of a third, or a clone the turn cut in two by a
14
+ // line written in its middle. A clone is the turn's only when the turn wrote in one of its sides.
10
15
 
11
16
  function refuse(): never {
12
17
  throw new Error("Not a jscpd report.");
13
18
  }
14
- function place(value: unknown): string {
19
+
20
+ /** A place in a file, as jscpd counts: lines from 1, columns from 0. */
21
+ interface Place {
22
+ line: number;
23
+ column: number;
24
+ }
25
+
26
+ /** One of the two sides of a clone: its file, and where it starts and ends, between two tokens. */
27
+ interface Side {
28
+ name: string;
29
+ start: Place;
30
+ end: Place;
31
+ }
32
+
33
+ function placeOf(value: unknown, line: number, column: number): Place {
34
+ if (isRecord(value) && typeof value.line === "number" && typeof value.column === "number")
35
+ return { line: value.line, column: value.column };
36
+ return { line, column };
37
+ }
38
+
39
+ // Without the columns of a clone, as from another jscpd, its first and last lines count as whole.
40
+ function sideOf(value: unknown): Side {
15
41
  if (!isRecord(value)) refuse();
16
- const { name, start, end } = value;
42
+ const { name, start, end, startLoc, endLoc } = value;
17
43
  if (typeof name !== "string" || typeof start !== "number" || typeof end !== "number") refuse();
18
- return `${name}:${start}-${end}`;
44
+ return { name, start: placeOf(startLoc, start, 0), end: placeOf(endLoc, end, Infinity) };
45
+ }
46
+
47
+ /**
48
+ * Whether the turn wrote in a side of a clone: a line it wrote stands whole in it, or it cut lines out of its middle.
49
+ * A clone starts and ends between two tokens, often inside a line: a line it only starts or ends in is not in it, nor
50
+ * an empty one, which jscpd does not read.
51
+ */
52
+ export function wroteIn({ start, end }: Pick<Side, "start" | "end">, text: string, written: WrittenLines[]): boolean {
53
+ const lines = text.split("\n");
54
+ const whole = (at: number) => {
55
+ const line = lines[at - 1] ?? "";
56
+ if (!line.trim()) return false;
57
+ const starts = at > start.line || (at === start.line && start.column <= line.length - line.trimStart().length);
58
+ const ends = at < end.line || (at === end.line && end.column >= line.trimEnd().length);
59
+ return starts && ends;
60
+ };
61
+ return written.some(({ at, lines: count }) =>
62
+ count === 0 ? start.line <= at && at < end.line : Array.from({ length: count }, (_, more) => at + more).some(whole),
63
+ );
19
64
  }
20
65
 
21
- export function newClones(report: unknown): string[] {
66
+ /** The clones jscpd calls new, each as its two sides. */
67
+ function newPairs(report: unknown): Side[][] {
22
68
  if (!isRecord(report) || !Array.isArray(report.duplicates)) refuse();
23
69
  return report.duplicates.flatMap((clone: unknown) => {
24
70
  if (!isRecord(clone)) refuse();
25
- const line = `${place(clone.firstFile)} ~ ${place(clone.secondFile)}`;
26
- return clone.isNew === true ? [line] : [];
71
+ const sides = [sideOf(clone.firstFile), sideOf(clone.secondFile)];
72
+ return clone.isNew === true ? [sides] : [];
27
73
  });
28
74
  }
29
75
 
30
- function main(root: string, turn: string): void {
76
+ /** The clones jscpd calls new, one per line, less the ones the turn wrote in neither side of. */
77
+ export function newClones(report: unknown, wrote: (side: Side) => boolean = () => true): string[] {
78
+ return newPairs(report)
79
+ .filter((sides) => sides.some(wrote))
80
+ .map((sides) => sides.map(({ name, start, end }) => `${name}:${start.line}-${end.line}`).join(" ~ "));
81
+ }
82
+
83
+ /**
84
+ * Whether the turn wrote in a side of a clone, for the clones of a report. Each file is read once, however many
85
+ * clones it has: the whole check finds every clone of the repo new.
86
+ */
87
+ function turnWrote(root: string, turn: string, report: unknown): (side: Side) => boolean {
88
+ const names = [...new Set(newPairs(report).flatMap((sides) => sides.map(({ name }) => name)))];
89
+ const old = new Set(filesAt(root, turn, names));
90
+ const files = new Map<string, { text: string; written: WrittenLines[] }>();
91
+ return (side) => {
92
+ // A file the turn created is all its own, and one jscpd names from another folder is unknown here: checking too
93
+ // much beats leaving a hole.
94
+ if (!old.has(side.name)) return true;
95
+ try {
96
+ const file = files.get(side.name) ?? {
97
+ text: readFileSync(join(root, side.name), "utf8"),
98
+ written: writtenSince(root, turn, side.name),
99
+ };
100
+ files.set(side.name, file);
101
+ return wroteIn(side, file.text, file.written);
102
+ } catch {
103
+ return true;
104
+ }
105
+ };
106
+ }
107
+
108
+ /** The clones the turn added to the repo, as jscpd finds them. It throws what jscpd said when jscpd fails. */
109
+ export function turnClones(root: string, turn: string): string[] {
31
110
  const jscpd = packageScript(root, "jscpd");
32
111
  if (jscpd === undefined)
33
112
  throw new Error("jscpd is not installed in node_modules: install the dependencies of the repo.");
@@ -42,17 +121,28 @@ function main(root: string, turn: string): void {
42
121
  } catch (error) {
43
122
  // What jscpd said, without the stack of this script around it.
44
123
  const said = isRecord(error) && typeof error.stderr === "string" ? error.stderr.trim() : String(error);
45
- console.log(`jscpd failed: ${said}`);
46
- process.exitCode = 1;
47
- return;
124
+ throw new Error(`jscpd failed: ${said}`, { cause: error });
48
125
  }
49
- const clones = newClones(readJsonFile(join(output, "jscpd-report.json")));
50
- if (!clones.length) return;
51
- console.log(headed("New clones: reuse the code already there, or factor it out.", clones));
52
- process.exitCode = 1;
126
+ const report = readJsonFile(join(output, "jscpd-report.json"));
127
+ return newClones(report, turnWrote(root, turn, report));
53
128
  } finally {
54
129
  rmSync(output, { recursive: true, force: true });
55
130
  }
56
131
  }
57
132
 
133
+ function main(root: string, turn: string): void {
134
+ let clones: string[];
135
+ try {
136
+ clones = turnClones(root, turn);
137
+ } catch (error) {
138
+ if (!(error instanceof Error) || !error.message.startsWith("jscpd failed: ")) throw error;
139
+ console.log(error.message);
140
+ process.exitCode = 1;
141
+ return;
142
+ }
143
+ if (!clones.length) return;
144
+ console.log(headed("New clones: reuse the code already there, or factor it out.", clones));
145
+ process.exitCode = 1;
146
+ }
147
+
58
148
  if (import.meta.main) main(process.cwd(), process.argv[2] ?? "HEAD");