@webpieces/rules-config 0.4.976 → 0.4.977

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": "@webpieces/rules-config",
3
- "version": "0.4.976",
3
+ "version": "0.4.977",
4
4
  "description": "Shared webpieces.config.json loader. Single source of truth for validation rule configuration consumed by @webpieces/ai-hook-rules, @webpieces/code-rules, and @webpieces/nx-webpieces-rules.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -19,9 +19,9 @@
19
19
  "inversify": "7.10.4",
20
20
  "reflect-metadata": "0.2.2",
21
21
  "minimatch": "10.0.1",
22
- "@webpieces/tooling-common": "0.4.976",
23
- "@webpieces/repo-workflow-core": "0.4.976",
24
- "@webpieces/rules-sdk": "0.4.976"
22
+ "@webpieces/tooling-common": "0.4.977",
23
+ "@webpieces/repo-workflow-core": "0.4.977",
24
+ "@webpieces/rules-sdk": "0.4.977"
25
25
  },
26
26
  "author": "Dean Hiller",
27
27
  "license": "Apache-2.0",
@@ -34,7 +34,7 @@
34
34
  "access": "public"
35
35
  },
36
36
  "devDependencies": {
37
- "@webpieces/tooling-testkit": "0.4.976"
37
+ "@webpieces/tooling-testkit": "0.4.977"
38
38
  },
39
39
  "types": "./src/index.d.ts",
40
40
  "bin": {
@@ -5,7 +5,12 @@
5
5
  * `@injectable(bindingScopeValues.Singleton)` so it can be injected and appear in the rules-config DI design. Free-function
6
6
  * delegators are kept temporarily so the many existing consumers stay green; they migrate to injecting
7
7
  * {@link DiffScope} over follow-up PRs, then the delegators are removed.
8
+ *
9
+ * Every git call goes through the injected {@link GitProcessApi} (#1381), so a program resolved from a
10
+ * container whose git edge is rebound to a mock reads its diff from scripted git. The free delegators below
11
+ * reach the REAL edge — a caller that is feature-tested injects DiffScope instead.
8
12
  */
13
+ import { GitProcessApi } from '@webpieces/tooling-common';
9
14
  /** A git diff range: the base ref to compare against and an optional head (else the working tree). */
10
15
  export declare class DiffRange {
11
16
  base?: string;
@@ -26,11 +31,13 @@ export declare class ChangedFilesOptions {
26
31
  includeDeletions?: boolean;
27
32
  }
28
33
  export declare class DiffScope {
34
+ private readonly git;
29
35
  private readonly ruleFileScope;
36
+ constructor(git?: GitProcessApi);
30
37
  /** Auto-detect the diff base: merge-base of HEAD with origin/main, falling back to local main. */
31
- detectBase(workspaceRoot: string): string | null;
38
+ detectBase(workspaceRoot: string): Promise<string | null>;
32
39
  /** Resolve the diff range a rule should compare against (honors nx's NX_BASE / NX_HEAD). */
33
- resolveBase(workspaceRoot: string): DiffRange;
40
+ resolveBase(workspaceRoot: string): Promise<DiffRange>;
34
41
  /**
35
42
  * Changed files between base and head (or base→working-tree when head is omitted). Untracked files
36
43
  * are unioned in for the working-tree case. `tsOnly` (default true) restricts to *.ts/*.tsx and
@@ -39,7 +46,7 @@ export declare class DiffScope {
39
46
  * Inside a rule run, the files that run's path exclusions match are dropped (#1253): this listing is
40
47
  * where the framework applies the top-level and per-rule `excludePaths`, so no rule does it itself.
41
48
  */
42
- getChangedFiles(workspaceRoot: string, base: string, head?: string, opts?: ChangedFilesOptions): string[];
49
+ getChangedFiles(workspaceRoot: string, base: string, head?: string, opts?: ChangedFilesOptions): Promise<string[]>;
43
50
  private listChangedFiles;
44
51
  /**
45
52
  * EVERY file in the working tree — tracked plus untracked-not-ignored, minus files deleted on disk —
@@ -54,10 +61,10 @@ export declare class DiffScope {
54
61
  *
55
62
  * Inside a rule run, the run's path exclusions are applied exactly as in {@link getChangedFiles}.
56
63
  */
57
- getAllFiles(workspaceRoot: string, opts?: ChangedFilesOptions): string[];
64
+ getAllFiles(workspaceRoot: string, opts?: ChangedFilesOptions): Promise<string[]>;
58
65
  private listAllFiles;
59
66
  /** Diff content for a single file (synthetic all-added diff for an untracked file with no head). */
60
- getFileDiff(workspaceRoot: string, file: string, base: string, head?: string): string;
67
+ getFileDiff(workspaceRoot: string, file: string, base: string, head?: string): Promise<string>;
61
68
  /** Added/changed line numbers (the `+` lines per hunk) — basis of NEW_AND_MODIFIED_CODE scoping. */
62
69
  getChangedLineNumbers(diffContent: string): Set<number>;
63
70
  /** Method names whose signature line is a `+` addition in the diff — the basis of "NEW" methods. */
@@ -68,10 +75,10 @@ export declare class DiffScope {
68
75
  isNewOrModified(name: string, startLine: number, endLine: number, changedLines: Set<number>, newMethodNames: Set<string>): boolean;
69
76
  private isTestFile;
70
77
  }
71
- export declare function detectBase(workspaceRoot: string): string | null;
72
- export declare function resolveBase(workspaceRoot: string): DiffRange;
73
- export declare function getChangedFiles(workspaceRoot: string, base: string, head?: string, opts?: ChangedFilesOptions): string[];
74
- export declare function getFileDiff(workspaceRoot: string, file: string, base: string, head?: string): string;
78
+ export declare function detectBase(workspaceRoot: string): Promise<string | null>;
79
+ export declare function resolveBase(workspaceRoot: string): Promise<DiffRange>;
80
+ export declare function getChangedFiles(workspaceRoot: string, base: string, head?: string, opts?: ChangedFilesOptions): Promise<string[]>;
81
+ export declare function getFileDiff(workspaceRoot: string, file: string, base: string, head?: string): Promise<string>;
75
82
  export declare function getChangedLineNumbers(diffContent: string): Set<number>;
76
83
  export declare function findNewMethodSignaturesInDiff(diffContent: string): Set<string>;
77
84
  export declare function hasChangesInRange(startLine: number, endLine: number, changedLines: Set<number>): boolean;
package/src/diff-scope.js CHANGED
@@ -6,6 +6,10 @@
6
6
  * `@injectable(bindingScopeValues.Singleton)` so it can be injected and appear in the rules-config DI design. Free-function
7
7
  * delegators are kept temporarily so the many existing consumers stay green; they migrate to injecting
8
8
  * {@link DiffScope} over follow-up PRs, then the delegators are removed.
9
+ *
10
+ * Every git call goes through the injected {@link GitProcessApi} (#1381), so a program resolved from a
11
+ * container whose git edge is rebound to a mock reads its diff from scripted git. The free delegators below
12
+ * reach the REAL edge — a caller that is feature-tested injects DiffScope instead.
9
13
  */
10
14
  Object.defineProperty(exports, "__esModule", { value: true });
11
15
  exports.DiffScope = exports.ChangedFilesOptions = exports.DiffRange = void 0;
@@ -18,11 +22,10 @@ exports.findNewMethodSignaturesInDiff = findNewMethodSignaturesInDiff;
18
22
  exports.hasChangesInRange = hasChangesInRange;
19
23
  exports.isNewOrModified = isNewOrModified;
20
24
  const tslib_1 = require("tslib");
21
- const child_process_1 = require("child_process");
22
25
  const fs = tslib_1.__importStar(require("fs"));
23
26
  const path = tslib_1.__importStar(require("path"));
24
27
  const inversify_1 = require("inversify");
25
- const to_error_1 = require("@webpieces/tooling-common/to-error");
28
+ const tooling_common_1 = require("@webpieces/tooling-common");
26
29
  const rule_file_scope_1 = require("./rule-file-scope");
27
30
  /** A git diff range: the base ref to compare against and an optional head (else the working tree). */
28
31
  class DiffRange {
@@ -46,33 +49,32 @@ class ChangedFilesOptions {
46
49
  }
47
50
  exports.ChangedFilesOptions = ChangedFilesOptions;
48
51
  let DiffScope = class DiffScope {
52
+ git;
49
53
  // Stateless reader of the rule run in progress (an AsyncLocalStorage store), not a dependency.
50
54
  ruleFileScope = new rule_file_scope_1.RuleFileScope();
55
+ // Defaulted so the free delegators below can `new DiffScope()`, while inversify injects the container's
56
+ // git edge — which is what a feature test rebinds.
57
+ constructor(git = new tooling_common_1.GitProcessClient()) {
58
+ this.git = git;
59
+ }
51
60
  /** Auto-detect the diff base: merge-base of HEAD with origin/main, falling back to local main. */
52
- detectBase(workspaceRoot) {
61
+ async detectBase(workspaceRoot) {
53
62
  for (const ref of ['origin/main', 'main']) {
54
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
55
- try {
56
- const merged = (0, child_process_1.execSync)(`git merge-base HEAD ${ref}`, {
57
- cwd: workspaceRoot, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'],
58
- }).trim();
59
- if (merged)
60
- return merged;
61
- }
62
- catch (err) {
63
- const error = (0, to_error_1.toError)(err);
64
- void error; // swallow — try the next ref
65
- }
63
+ // A failure (no such ref, not a repo) just tries the next ref.
64
+ const result = await this.git.run(['merge-base', 'HEAD', ref], workspaceRoot);
65
+ const merged = result.ok ? result.stdout.trim() : '';
66
+ if (merged)
67
+ return merged;
66
68
  }
67
69
  return null;
68
70
  }
69
71
  /** Resolve the diff range a rule should compare against (honors nx's NX_BASE / NX_HEAD). */
70
- resolveBase(workspaceRoot) {
72
+ async resolveBase(workspaceRoot) {
71
73
  const range = new DiffRange();
72
74
  range.base = process.env['NX_BASE'];
73
75
  range.head = process.env['NX_HEAD'];
74
76
  if (!range.base) {
75
- range.base = this.detectBase(workspaceRoot) ?? undefined;
77
+ range.base = (await this.detectBase(workspaceRoot)) ?? undefined;
76
78
  }
77
79
  return range;
78
80
  }
@@ -84,49 +86,31 @@ let DiffScope = class DiffScope {
84
86
  * Inside a rule run, the files that run's path exclusions match are dropped (#1253): this listing is
85
87
  * where the framework applies the top-level and per-rule `excludePaths`, so no rule does it itself.
86
88
  */
87
- getChangedFiles(workspaceRoot, base, head, opts) {
88
- return this.ruleFileScope.filter(this.listChangedFiles(workspaceRoot, base, head, opts));
89
+ async getChangedFiles(workspaceRoot, base, head, opts) {
90
+ return this.ruleFileScope.filter(await this.listChangedFiles(workspaceRoot, base, head, opts));
89
91
  }
90
- // webpieces-disable max-lines-new-methods -- git command handling with untracked files needs several code paths
91
- listChangedFiles(workspaceRoot, base, head, opts) {
92
+ async listChangedFiles(workspaceRoot, base, head, opts) {
92
93
  const tsOnly = opts?.tsOnly ?? true;
93
- const glob = tsOnly ? " -- '*.ts' '*.tsx'" : '';
94
+ const glob = tsOnly ? ['--', '*.ts', '*.tsx'] : [];
94
95
  const keep = (f) => f.length > 0 && (!tsOnly || !this.isTestFile(f));
95
96
  // Deletions are excluded by default (see ChangedFilesOptions.includeDeletions) — the review flow
96
97
  // opts in, every lint validator keeps the historical filter.
97
- const filter = opts?.includeDeletions === true ? '' : ' --diff-filter=d';
98
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
99
- try {
100
- const diffTarget = head ? `${base} ${head}` : base;
101
- const output = (0, child_process_1.execSync)(`git diff --name-only${filter} ${diffTarget}${glob}`, {
102
- cwd: workspaceRoot,
103
- encoding: 'utf-8',
104
- });
105
- const changedFiles = output.trim().split('\n').filter(keep);
106
- // Working-tree comparison (no head): also include untracked files, as nx affected does.
107
- if (!head) {
108
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
109
- try {
110
- const untrackedOutput = (0, child_process_1.execSync)(`git ls-files --others --exclude-standard${glob}`, {
111
- cwd: workspaceRoot,
112
- encoding: 'utf-8',
113
- });
114
- const untrackedFiles = untrackedOutput.trim().split('\n').filter(keep);
115
- return Array.from(new Set([...changedFiles, ...untrackedFiles]));
116
- }
117
- catch (err) {
118
- const error = (0, to_error_1.toError)(err);
119
- void error; // swallow — ls-files failure falls back to the tracked list
120
- return changedFiles;
121
- }
122
- }
123
- return changedFiles;
124
- }
125
- catch (err) {
126
- const error = (0, to_error_1.toError)(err);
127
- void error; // swallow — git diff failure returns an empty list
98
+ const filter = opts?.includeDeletions === true ? [] : ['--diff-filter=d'];
99
+ const diffTarget = head ? [base, head] : [base];
100
+ const diff = await this.git.run(['diff', '--name-only', ...filter, ...diffTarget, ...glob], workspaceRoot);
101
+ // A failed `git diff` returns an empty list.
102
+ if (!diff.ok)
128
103
  return [];
129
- }
104
+ const changedFiles = diff.stdout.trim().split('\n').filter(keep);
105
+ // Working-tree comparison (no head): also include untracked files, as nx affected does.
106
+ if (head)
107
+ return changedFiles;
108
+ const untracked = await this.git.run(['ls-files', '--others', '--exclude-standard', ...glob], workspaceRoot);
109
+ // An `ls-files` failure falls back to the tracked list.
110
+ if (!untracked.ok)
111
+ return changedFiles;
112
+ const untrackedFiles = untracked.stdout.trim().split('\n').filter(keep);
113
+ return Array.from(new Set([...changedFiles, ...untrackedFiles]));
130
114
  }
131
115
  /**
132
116
  * EVERY file in the working tree — tracked plus untracked-not-ignored, minus files deleted on disk —
@@ -141,49 +125,39 @@ let DiffScope = class DiffScope {
141
125
  *
142
126
  * Inside a rule run, the run's path exclusions are applied exactly as in {@link getChangedFiles}.
143
127
  */
144
- getAllFiles(workspaceRoot, opts) {
145
- return this.ruleFileScope.filter(this.listAllFiles(workspaceRoot, opts));
128
+ async getAllFiles(workspaceRoot, opts) {
129
+ return this.ruleFileScope.filter(await this.listAllFiles(workspaceRoot, opts));
146
130
  }
147
- listAllFiles(workspaceRoot, opts) {
131
+ async listAllFiles(workspaceRoot, opts) {
148
132
  const tsOnly = opts?.tsOnly ?? true;
149
- const glob = tsOnly ? " -- '*.ts' '*.tsx'" : '';
150
- const output = (0, child_process_1.execSync)(`git ls-files --cached --others --exclude-standard${glob}`, {
151
- cwd: workspaceRoot,
152
- encoding: 'utf-8',
153
- maxBuffer: 256 * 1024 * 1024,
154
- });
133
+ const glob = tsOnly ? ['--', '*.ts', '*.tsx'] : [];
134
+ const listed = await this.git.run(['ls-files', '--cached', '--others', '--exclude-standard', ...glob], workspaceRoot);
135
+ if (!listed.ok) {
136
+ throw new tooling_common_1.InformAiError(`\`git ls-files\` failed in ${workspaceRoot} (exit ${String(listed.code)}): ${listed.stderr.trim()}. `
137
+ + 'A whole-scope rule run cannot list the working tree; repair git access there, then retry.');
138
+ }
139
+ const output = listed.stdout;
155
140
  const keep = (f) => f.length > 0 && (!tsOnly || !this.isTestFile(f)) && fs.existsSync(path.join(workspaceRoot, f));
156
141
  return Array.from(new Set(output.trim().split('\n').filter(keep)));
157
142
  }
158
143
  /** Diff content for a single file (synthetic all-added diff for an untracked file with no head). */
159
- getFileDiff(workspaceRoot, file, base, head) {
160
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
161
- try {
162
- const diffTarget = head ? `${base} ${head}` : base;
163
- const diff = (0, child_process_1.execSync)(`git diff ${diffTarget} -- "${file}"`, {
164
- cwd: workspaceRoot,
165
- encoding: 'utf-8',
166
- });
167
- if (!diff && !head) {
168
- const fullPath = path.join(workspaceRoot, file);
169
- if (fs.existsSync(fullPath)) {
170
- const isUntracked = (0, child_process_1.execSync)(`git ls-files --others --exclude-standard "${file}"`, {
171
- cwd: workspaceRoot,
172
- encoding: 'utf-8',
173
- }).trim();
174
- if (isUntracked) {
175
- const content = fs.readFileSync(fullPath, 'utf-8');
176
- return content.split('\n').map((l) => `+${l}`).join('\n');
177
- }
178
- }
179
- }
180
- return diff;
181
- }
182
- catch (err) {
183
- const error = (0, to_error_1.toError)(err);
184
- void error; // swallow — git diff failure returns no diff
144
+ async getFileDiff(workspaceRoot, file, base, head) {
145
+ const diffTarget = head ? [base, head] : [base];
146
+ const result = await this.git.run(['diff', ...diffTarget, '--', file], workspaceRoot);
147
+ // A failed `git diff` returns no diff.
148
+ if (!result.ok)
185
149
  return '';
186
- }
150
+ const diff = result.stdout;
151
+ if (diff || head)
152
+ return diff;
153
+ const fullPath = path.join(workspaceRoot, file);
154
+ if (!fs.existsSync(fullPath))
155
+ return diff;
156
+ const untracked = await this.git.run(['ls-files', '--others', '--exclude-standard', '--', file], workspaceRoot);
157
+ if (!untracked.ok || untracked.stdout.trim() === '')
158
+ return diff;
159
+ const content = fs.readFileSync(fullPath, 'utf-8');
160
+ return content.split('\n').map((l) => `+${l}`).join('\n');
187
161
  }
188
162
  /** Added/changed line numbers (the `+` lines per hunk) — basis of NEW_AND_MODIFIED_CODE scoping. */
189
163
  getChangedLineNumbers(diffContent) {
@@ -258,7 +232,8 @@ let DiffScope = class DiffScope {
258
232
  };
259
233
  exports.DiffScope = DiffScope;
260
234
  exports.DiffScope = DiffScope = tslib_1.__decorate([
261
- (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton)
235
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
236
+ tslib_1.__metadata("design:paramtypes", [tooling_common_1.GitProcessApi])
262
237
  ], DiffScope);
263
238
  // Temporary migration delegators to DiffScope — removed once consumers inject it.
264
239
  const diffScopeSvc = new DiffScope();
@@ -1 +1 @@
1
- {"version":3,"file":"diff-scope.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/diff-scope.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AA+QH,g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C;AAClD,CAAC;AAED,gIAAgI;AAChI,SAAgB,WAAW,CAAC,aAAqB;IAC7C,OAAO,YAAY,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;AACnD,CAAC;AAED,gIAAgI;AAChI,SAAgB,eAAe,CAAC,aAAqB,EAAE,IAAY,EAAE,IAAa,EAAE,IAA0B;IAC1G,OAAO,YAAY,CAAC,eAAe,CAAC,aAAa,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AACzE,CAAC;AAED,gIAAgI;AAChI,SAAgB,WAAW,CAAC,aAAqB,EAAE,IAAY,EAAE,IAAY,EAAE,IAAa;IACxF,OAAO,YAAY,CAAC,WAAW,CAAC,aAAa,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AACrE,CAAC;AAED,gIAAgI;AAChI,SAAgB,qBAAqB,CAAC,WAAmB;IACrD,OAAO,YAAY,CAAC,qBAAqB,CAAC,WAAW,CAAC,CAAC;AAC3D,CAAC;AAED,gIAAgI;AAChI,SAAgB,6BAA6B,CAAC,WAAmB;IAC7D,OAAO,YAAY,CAAC,6BAA6B,CAAC,WAAW,CAAC,CAAC;AACnE,CAAC;AAED,gIAAgI;AAChI,SAAgB,iBAAiB,CAAC,SAAiB,EAAE,OAAe,EAAE,YAAyB;IAC3F,OAAO,YAAY,CAAC,iBAAiB,CAAC,SAAS,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC;AAC5E,CAAC;AAED,gIAAgI;AAChI,SAAgB,eAAe,CAC3B,IAAY,EACZ,SAAiB,EACjB,OAAe,EACf,YAAyB,EACzB,cAA2B;IAE3B,OAAO,YAAY,CAAC,eAAe,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,YAAY,EAAE,cAAc,CAAC,CAAC;AAChG,CAAC","sourcesContent":["/**\n * Shared git-diff + diff-scoping service for ALL rule validators (code-rules) and nx executors\n * (nx-webpieces-rules). Centralized here in rules-config because it is the one package both depend on.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it can be injected and appear in the rules-config DI design. Free-function\n * delegators are kept temporarily so the many existing consumers stay green; they migrate to injecting\n * {@link DiffScope} over follow-up PRs, then the delegators are removed.\n */\n\nimport { execSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\n\nimport { RuleFileScope } from './rule-file-scope';\n\n/** A git diff range: the base ref to compare against and an optional head (else the working tree). */\nexport class DiffRange {\n base?: string;\n head?: string;\n}\n\n/** Options for getChangedFiles. `tsOnly` (default true) restricts to *.ts/*.tsx and drops test files. */\nexport class ChangedFilesOptions {\n tsOnly?: boolean;\n /**\n * Include DELETED files in the result. Default false, which is `--diff-filter=d` — the historical\n * behavior, kept as the default so every existing caller is byte-identical.\n *\n * The default is right for lint validators (you cannot lint a file that is gone) and WRONG for checklist\n * matching: a PR that DELETES a migration, an auth check or a terraform rule changed exactly the thing a\n * checklist exists to catch, and dropping it from the changed-file set means the checklist never fires\n * and no reviewer is ever asked. The review flow sets this true.\n */\n includeDeletions?: boolean;\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class DiffScope {\n // Stateless reader of the rule run in progress (an AsyncLocalStorage store), not a dependency.\n private readonly ruleFileScope = new RuleFileScope();\n\n /** Auto-detect the diff base: merge-base of HEAD with origin/main, falling back to local main. */\n detectBase(workspaceRoot: string): string | null {\n for (const ref of ['origin/main', 'main']) {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const merged = execSync(`git merge-base HEAD ${ref}`, {\n cwd: workspaceRoot, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'],\n }).trim();\n if (merged) return merged;\n } catch (err: unknown) {\n const error = toError(err);\n void error; // swallow — try the next ref\n }\n }\n return null;\n }\n\n /** Resolve the diff range a rule should compare against (honors nx's NX_BASE / NX_HEAD). */\n resolveBase(workspaceRoot: string): DiffRange {\n const range = new DiffRange();\n range.base = process.env['NX_BASE'];\n range.head = process.env['NX_HEAD'];\n if (!range.base) {\n range.base = this.detectBase(workspaceRoot) ?? undefined;\n }\n return range;\n }\n\n /**\n * Changed files between base and head (or base→working-tree when head is omitted). Untracked files\n * are unioned in for the working-tree case. `tsOnly` (default true) restricts to *.ts/*.tsx and\n * drops test files. Deletions are excluded (`--diff-filter=d`).\n *\n * Inside a rule run, the files that run's path exclusions match are dropped (#1253): this listing is\n * where the framework applies the top-level and per-rule `excludePaths`, so no rule does it itself.\n */\n getChangedFiles(workspaceRoot: string, base: string, head?: string, opts?: ChangedFilesOptions): string[] {\n return this.ruleFileScope.filter(this.listChangedFiles(workspaceRoot, base, head, opts));\n }\n\n // webpieces-disable max-lines-new-methods -- git command handling with untracked files needs several code paths\n private listChangedFiles(workspaceRoot: string, base: string, head?: string, opts?: ChangedFilesOptions): string[] {\n const tsOnly = opts?.tsOnly ?? true;\n const glob = tsOnly ? \" -- '*.ts' '*.tsx'\" : '';\n const keep = (f: string): boolean => f.length > 0 && (!tsOnly || !this.isTestFile(f));\n // Deletions are excluded by default (see ChangedFilesOptions.includeDeletions) — the review flow\n // opts in, every lint validator keeps the historical filter.\n const filter = opts?.includeDeletions === true ? '' : ' --diff-filter=d';\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const diffTarget = head ? `${base} ${head}` : base;\n const output = execSync(`git diff --name-only${filter} ${diffTarget}${glob}`, {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n });\n const changedFiles = output.trim().split('\\n').filter(keep);\n\n // Working-tree comparison (no head): also include untracked files, as nx affected does.\n if (!head) {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const untrackedOutput = execSync(`git ls-files --others --exclude-standard${glob}`, {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n });\n const untrackedFiles = untrackedOutput.trim().split('\\n').filter(keep);\n return Array.from(new Set([...changedFiles, ...untrackedFiles]));\n } catch (err: unknown) {\n const error = toError(err);\n void error; // swallow — ls-files failure falls back to the tracked list\n return changedFiles;\n }\n }\n\n return changedFiles;\n } catch (err: unknown) {\n const error = toError(err);\n void error; // swallow — git diff failure returns an empty list\n return [];\n }\n }\n\n /**\n * EVERY file in the working tree — tracked plus untracked-not-ignored, minus files deleted on disk —\n * filtered exactly like {@link getChangedFiles} (`tsOnly` default true: *.ts/*.tsx, no test files).\n * The file set of the whole-scope modes (#1027): RUN_EVERY_TIME judges all of it, MODIFIED_PROJECTS the\n * part owned by a touched project. Git, not a directory walk, so `.gitignore` (node_modules, dist)\n * is honoured for free.\n *\n * Unlike getChangedFiles it does NOT swallow a git failure into an empty list: an empty whole-scope\n * listing reads as \"0 sites left\", a false answer to exactly the question these modes exist to\n * answer, so a failed `git ls-files` throws and fails the run.\n *\n * Inside a rule run, the run's path exclusions are applied exactly as in {@link getChangedFiles}.\n */\n getAllFiles(workspaceRoot: string, opts?: ChangedFilesOptions): string[] {\n return this.ruleFileScope.filter(this.listAllFiles(workspaceRoot, opts));\n }\n\n private listAllFiles(workspaceRoot: string, opts?: ChangedFilesOptions): string[] {\n const tsOnly = opts?.tsOnly ?? true;\n const glob = tsOnly ? \" -- '*.ts' '*.tsx'\" : '';\n const output = execSync(`git ls-files --cached --others --exclude-standard${glob}`, {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n maxBuffer: 256 * 1024 * 1024,\n });\n const keep = (f: string): boolean =>\n f.length > 0 && (!tsOnly || !this.isTestFile(f)) && fs.existsSync(path.join(workspaceRoot, f));\n return Array.from(new Set(output.trim().split('\\n').filter(keep)));\n }\n\n /** Diff content for a single file (synthetic all-added diff for an untracked file with no head). */\n getFileDiff(workspaceRoot: string, file: string, base: string, head?: string): string {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const diffTarget = head ? `${base} ${head}` : base;\n const diff = execSync(`git diff ${diffTarget} -- \"${file}\"`, {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n });\n\n if (!diff && !head) {\n const fullPath = path.join(workspaceRoot, file);\n if (fs.existsSync(fullPath)) {\n const isUntracked = execSync(`git ls-files --others --exclude-standard \"${file}\"`, {\n cwd: workspaceRoot,\n encoding: 'utf-8',\n }).trim();\n\n if (isUntracked) {\n const content = fs.readFileSync(fullPath, 'utf-8');\n return content.split('\\n').map((l: string) => `+${l}`).join('\\n');\n }\n }\n }\n\n return diff;\n } catch (err: unknown) {\n const error = toError(err);\n void error; // swallow — git diff failure returns no diff\n return '';\n }\n }\n\n /** Added/changed line numbers (the `+` lines per hunk) — basis of NEW_AND_MODIFIED_CODE scoping. */\n getChangedLineNumbers(diffContent: string): Set<number> {\n const changedLines = new Set<number>();\n const lines = diffContent.split('\\n');\n let currentLine = 0;\n\n for (const line of lines) {\n const hunkMatch = line.match(/^@@ -\\d+(?:,\\d+)? \\+(\\d+)(?:,\\d+)? @@/);\n if (hunkMatch) {\n currentLine = parseInt(hunkMatch[1], 10);\n continue;\n }\n\n if (line.startsWith('+') && !line.startsWith('+++')) {\n changedLines.add(currentLine);\n currentLine++;\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n // Deletions don't advance the new-file line counter.\n } else {\n currentLine++;\n }\n }\n\n return changedLines;\n }\n\n /** Method names whose signature line is a `+` addition in the diff — the basis of \"NEW\" methods. */\n findNewMethodSignaturesInDiff(diffContent: string): Set<string> {\n const newMethods = new Set<string>();\n const lines = diffContent.split('\\n');\n\n const patterns = [\n /^\\+\\s*(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)\\s*\\(/,\n /^\\+\\s*(?:export\\s+)?(?:const|let)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\(/,\n /^\\+\\s*(?:export\\s+)?(?:const|let)\\s+(\\w+)\\s*=\\s*(?:async\\s+)?function/,\n /^\\+\\s*(?:(?:public|private|protected)\\s+)?(?:static\\s+)?(?:async\\s+)?(\\w+)\\s*\\(/,\n ];\n\n for (const line of lines) {\n if (line.startsWith('+') && !line.startsWith('+++')) {\n for (const pattern of patterns) {\n const match = line.match(pattern);\n if (match) {\n const methodName = match[1];\n if (methodName && !['if', 'for', 'while', 'switch', 'catch', 'constructor'].includes(methodName)) {\n newMethods.add(methodName);\n }\n break;\n }\n }\n }\n }\n\n return newMethods;\n }\n\n /** True if any line in [startLine, endLine] is in the changedLines set. */\n hasChangesInRange(startLine: number, endLine: number, changedLines: Set<number>): boolean {\n for (let line = startLine; line <= endLine; line++) {\n if (changedLines.has(line)) {\n return true;\n }\n }\n return false;\n }\n\n /** True if a node (method/function) is newly added or has any changed line in its range. */\n isNewOrModified(\n name: string,\n startLine: number,\n endLine: number,\n changedLines: Set<number>,\n newMethodNames: Set<string>,\n ): boolean {\n if (newMethodNames.has(name)) return true;\n return this.hasChangesInRange(startLine, endLine, changedLines);\n }\n\n // A file is \"a test file\" (excluded from diff-scoped rules) when it is a .spec/.test file or lives\n // under a __tests__/ directory.\n private isTestFile(file: string): boolean {\n return file.includes('.spec.ts') || file.includes('.test.ts') || file.includes('__tests__/');\n }\n}\n\n// Temporary migration delegators to DiffScope — removed once consumers inject it.\nconst diffScopeSvc = new DiffScope();\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to DiffScope; removed once consumers inject it\nexport function detectBase(workspaceRoot: string): string | null {\n return diffScopeSvc.detectBase(workspaceRoot);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to DiffScope; removed once consumers inject it\nexport function resolveBase(workspaceRoot: string): DiffRange {\n return diffScopeSvc.resolveBase(workspaceRoot);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to DiffScope; removed once consumers inject it\nexport function getChangedFiles(workspaceRoot: string, base: string, head?: string, opts?: ChangedFilesOptions): string[] {\n return diffScopeSvc.getChangedFiles(workspaceRoot, base, head, opts);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to DiffScope; removed once consumers inject it\nexport function getFileDiff(workspaceRoot: string, file: string, base: string, head?: string): string {\n return diffScopeSvc.getFileDiff(workspaceRoot, file, base, head);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to DiffScope; removed once consumers inject it\nexport function getChangedLineNumbers(diffContent: string): Set<number> {\n return diffScopeSvc.getChangedLineNumbers(diffContent);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to DiffScope; removed once consumers inject it\nexport function findNewMethodSignaturesInDiff(diffContent: string): Set<string> {\n return diffScopeSvc.findNewMethodSignaturesInDiff(diffContent);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to DiffScope; removed once consumers inject it\nexport function hasChangesInRange(startLine: number, endLine: number, changedLines: Set<number>): boolean {\n return diffScopeSvc.hasChangesInRange(startLine, endLine, changedLines);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to DiffScope; removed once consumers inject it\nexport function isNewOrModified(\n name: string,\n startLine: number,\n endLine: number,\n changedLines: Set<number>,\n newMethodNames: Set<string>,\n): boolean {\n return diffScopeSvc.isNewOrModified(name, startLine, endLine, changedLines, newMethodNames);\n}\n"]}
1
+ {"version":3,"file":"diff-scope.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/diff-scope.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;GAWG;;;AA0OH,gCAEC;AAGD,kCAEC;AAGD,0CAEC;AAGD,kCAEC;AAGD,sDAEC;AAGD,sEAEC;AAGD,8CAEC;AAGD,0CAQC;;AAnRD,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,8DAA2F;AAE3F,uDAAkD;AAElD,sGAAsG;AACtG,MAAa,SAAS;IAClB,IAAI,CAAU;IACd,IAAI,CAAU;CACjB;AAHD,8BAGC;AAED,yGAAyG;AACzG,MAAa,mBAAmB;IAC5B,MAAM,CAAW;IACjB;;;;;;;;OAQG;IACH,gBAAgB,CAAW;CAC9B;AAZD,kDAYC;AAGM,IAAM,SAAS,GAAf,MAAM,SAAS;IAMW;IAL7B,+FAA+F;IAC9E,aAAa,GAAG,IAAI,+BAAa,EAAE,CAAC;IAErD,wGAAwG;IACxG,m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,IAAY,EAAE,IAAa;IACxF,OAAO,YAAY,CAAC,WAAW,CAAC,aAAa,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AACrE,CAAC;AAED,gIAAgI;AAChI,SAAgB,qBAAqB,CAAC,WAAmB;IACrD,OAAO,YAAY,CAAC,qBAAqB,CAAC,WAAW,CAAC,CAAC;AAC3D,CAAC;AAED,gIAAgI;AAChI,SAAgB,6BAA6B,CAAC,WAAmB;IAC7D,OAAO,YAAY,CAAC,6BAA6B,CAAC,WAAW,CAAC,CAAC;AACnE,CAAC;AAED,gIAAgI;AAChI,SAAgB,iBAAiB,CAAC,SAAiB,EAAE,OAAe,EAAE,YAAyB;IAC3F,OAAO,YAAY,CAAC,iBAAiB,CAAC,SAAS,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC;AAC5E,CAAC;AAED,gIAAgI;AAChI,SAAgB,eAAe,CAC3B,IAAY,EACZ,SAAiB,EACjB,OAAe,EACf,YAAyB,EACzB,cAA2B;IAE3B,OAAO,YAAY,CAAC,eAAe,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,YAAY,EAAE,cAAc,CAAC,CAAC;AAChG,CAAC","sourcesContent":["/**\n * Shared git-diff + diff-scoping service for ALL rule validators (code-rules) and nx executors\n * (nx-webpieces-rules). Centralized here in rules-config because it is the one package both depend on.\n *\n * `@injectable(bindingScopeValues.Singleton)` so it can be injected and appear in the rules-config DI design. Free-function\n * delegators are kept temporarily so the many existing consumers stay green; they migrate to injecting\n * {@link DiffScope} over follow-up PRs, then the delegators are removed.\n *\n * Every git call goes through the injected {@link GitProcessApi} (#1381), so a program resolved from a\n * container whose git edge is rebound to a mock reads its diff from scripted git. The free delegators below\n * reach the REAL edge — a caller that is feature-tested injects DiffScope instead.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { GitProcessApi, GitProcessClient, InformAiError } from '@webpieces/tooling-common';\n\nimport { RuleFileScope } from './rule-file-scope';\n\n/** A git diff range: the base ref to compare against and an optional head (else the working tree). */\nexport class DiffRange {\n base?: string;\n head?: string;\n}\n\n/** Options for getChangedFiles. `tsOnly` (default true) restricts to *.ts/*.tsx and drops test files. */\nexport class ChangedFilesOptions {\n tsOnly?: boolean;\n /**\n * Include DELETED files in the result. Default false, which is `--diff-filter=d` — the historical\n * behavior, kept as the default so every existing caller is byte-identical.\n *\n * The default is right for lint validators (you cannot lint a file that is gone) and WRONG for checklist\n * matching: a PR that DELETES a migration, an auth check or a terraform rule changed exactly the thing a\n * checklist exists to catch, and dropping it from the changed-file set means the checklist never fires\n * and no reviewer is ever asked. The review flow sets this true.\n */\n includeDeletions?: boolean;\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class DiffScope {\n // Stateless reader of the rule run in progress (an AsyncLocalStorage store), not a dependency.\n private readonly ruleFileScope = new RuleFileScope();\n\n // Defaulted so the free delegators below can `new DiffScope()`, while inversify injects the container's\n // git edge — which is what a feature test rebinds.\n constructor(private readonly git: GitProcessApi = new GitProcessClient()) {}\n\n /** Auto-detect the diff base: merge-base of HEAD with origin/main, falling back to local main. */\n async detectBase(workspaceRoot: string): Promise<string | null> {\n for (const ref of ['origin/main', 'main']) {\n // A failure (no such ref, not a repo) just tries the next ref.\n const result = await this.git.run(['merge-base', 'HEAD', ref], workspaceRoot);\n const merged = result.ok ? result.stdout.trim() : '';\n if (merged) return merged;\n }\n return null;\n }\n\n /** Resolve the diff range a rule should compare against (honors nx's NX_BASE / NX_HEAD). */\n async resolveBase(workspaceRoot: string): Promise<DiffRange> {\n const range = new DiffRange();\n range.base = process.env['NX_BASE'];\n range.head = process.env['NX_HEAD'];\n if (!range.base) {\n range.base = (await this.detectBase(workspaceRoot)) ?? undefined;\n }\n return range;\n }\n\n /**\n * Changed files between base and head (or base→working-tree when head is omitted). Untracked files\n * are unioned in for the working-tree case. `tsOnly` (default true) restricts to *.ts/*.tsx and\n * drops test files. Deletions are excluded (`--diff-filter=d`).\n *\n * Inside a rule run, the files that run's path exclusions match are dropped (#1253): this listing is\n * where the framework applies the top-level and per-rule `excludePaths`, so no rule does it itself.\n */\n async getChangedFiles(workspaceRoot: string, base: string, head?: string, opts?: ChangedFilesOptions): Promise<string[]> {\n return this.ruleFileScope.filter(await this.listChangedFiles(workspaceRoot, base, head, opts));\n }\n\n private async listChangedFiles(workspaceRoot: string, base: string, head?: string, opts?: ChangedFilesOptions): Promise<string[]> {\n const tsOnly = opts?.tsOnly ?? true;\n const glob = tsOnly ? ['--', '*.ts', '*.tsx'] : [];\n const keep = (f: string): boolean => f.length > 0 && (!tsOnly || !this.isTestFile(f));\n // Deletions are excluded by default (see ChangedFilesOptions.includeDeletions) — the review flow\n // opts in, every lint validator keeps the historical filter.\n const filter = opts?.includeDeletions === true ? [] : ['--diff-filter=d'];\n const diffTarget = head ? [base, head] : [base];\n const diff = await this.git.run(['diff', '--name-only', ...filter, ...diffTarget, ...glob], workspaceRoot);\n // A failed `git diff` returns an empty list.\n if (!diff.ok) return [];\n const changedFiles = diff.stdout.trim().split('\\n').filter(keep);\n\n // Working-tree comparison (no head): also include untracked files, as nx affected does.\n if (head) return changedFiles;\n const untracked = await this.git.run(['ls-files', '--others', '--exclude-standard', ...glob], workspaceRoot);\n // An `ls-files` failure falls back to the tracked list.\n if (!untracked.ok) return changedFiles;\n const untrackedFiles = untracked.stdout.trim().split('\\n').filter(keep);\n return Array.from(new Set([...changedFiles, ...untrackedFiles]));\n }\n\n /**\n * EVERY file in the working tree — tracked plus untracked-not-ignored, minus files deleted on disk —\n * filtered exactly like {@link getChangedFiles} (`tsOnly` default true: *.ts/*.tsx, no test files).\n * The file set of the whole-scope modes (#1027): RUN_EVERY_TIME judges all of it, MODIFIED_PROJECTS the\n * part owned by a touched project. Git, not a directory walk, so `.gitignore` (node_modules, dist)\n * is honoured for free.\n *\n * Unlike getChangedFiles it does NOT swallow a git failure into an empty list: an empty whole-scope\n * listing reads as \"0 sites left\", a false answer to exactly the question these modes exist to\n * answer, so a failed `git ls-files` throws and fails the run.\n *\n * Inside a rule run, the run's path exclusions are applied exactly as in {@link getChangedFiles}.\n */\n async getAllFiles(workspaceRoot: string, opts?: ChangedFilesOptions): Promise<string[]> {\n return this.ruleFileScope.filter(await this.listAllFiles(workspaceRoot, opts));\n }\n\n private async listAllFiles(workspaceRoot: string, opts?: ChangedFilesOptions): Promise<string[]> {\n const tsOnly = opts?.tsOnly ?? true;\n const glob = tsOnly ? ['--', '*.ts', '*.tsx'] : [];\n const listed = await this.git.run(['ls-files', '--cached', '--others', '--exclude-standard', ...glob], workspaceRoot);\n if (!listed.ok) {\n throw new InformAiError(\n `\\`git ls-files\\` failed in ${workspaceRoot} (exit ${String(listed.code)}): ${listed.stderr.trim()}. `\n + 'A whole-scope rule run cannot list the working tree; repair git access there, then retry.');\n }\n const output = listed.stdout;\n const keep = (f: string): boolean =>\n f.length > 0 && (!tsOnly || !this.isTestFile(f)) && fs.existsSync(path.join(workspaceRoot, f));\n return Array.from(new Set(output.trim().split('\\n').filter(keep)));\n }\n\n /** Diff content for a single file (synthetic all-added diff for an untracked file with no head). */\n async getFileDiff(workspaceRoot: string, file: string, base: string, head?: string): Promise<string> {\n const diffTarget = head ? [base, head] : [base];\n const result = await this.git.run(['diff', ...diffTarget, '--', file], workspaceRoot);\n // A failed `git diff` returns no diff.\n if (!result.ok) return '';\n const diff = result.stdout;\n if (diff || head) return diff;\n\n const fullPath = path.join(workspaceRoot, file);\n if (!fs.existsSync(fullPath)) return diff;\n const untracked = await this.git.run(['ls-files', '--others', '--exclude-standard', '--', file], workspaceRoot);\n if (!untracked.ok || untracked.stdout.trim() === '') return diff;\n const content = fs.readFileSync(fullPath, 'utf-8');\n return content.split('\\n').map((l: string) => `+${l}`).join('\\n');\n }\n\n /** Added/changed line numbers (the `+` lines per hunk) — basis of NEW_AND_MODIFIED_CODE scoping. */\n getChangedLineNumbers(diffContent: string): Set<number> {\n const changedLines = new Set<number>();\n const lines = diffContent.split('\\n');\n let currentLine = 0;\n\n for (const line of lines) {\n const hunkMatch = line.match(/^@@ -\\d+(?:,\\d+)? \\+(\\d+)(?:,\\d+)? @@/);\n if (hunkMatch) {\n currentLine = parseInt(hunkMatch[1], 10);\n continue;\n }\n\n if (line.startsWith('+') && !line.startsWith('+++')) {\n changedLines.add(currentLine);\n currentLine++;\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n // Deletions don't advance the new-file line counter.\n } else {\n currentLine++;\n }\n }\n\n return changedLines;\n }\n\n /** Method names whose signature line is a `+` addition in the diff — the basis of \"NEW\" methods. */\n findNewMethodSignaturesInDiff(diffContent: string): Set<string> {\n const newMethods = new Set<string>();\n const lines = diffContent.split('\\n');\n\n const patterns = [\n /^\\+\\s*(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)\\s*\\(/,\n /^\\+\\s*(?:export\\s+)?(?:const|let)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\(/,\n /^\\+\\s*(?:export\\s+)?(?:const|let)\\s+(\\w+)\\s*=\\s*(?:async\\s+)?function/,\n /^\\+\\s*(?:(?:public|private|protected)\\s+)?(?:static\\s+)?(?:async\\s+)?(\\w+)\\s*\\(/,\n ];\n\n for (const line of lines) {\n if (line.startsWith('+') && !line.startsWith('+++')) {\n for (const pattern of patterns) {\n const match = line.match(pattern);\n if (match) {\n const methodName = match[1];\n if (methodName && !['if', 'for', 'while', 'switch', 'catch', 'constructor'].includes(methodName)) {\n newMethods.add(methodName);\n }\n break;\n }\n }\n }\n }\n\n return newMethods;\n }\n\n /** True if any line in [startLine, endLine] is in the changedLines set. */\n hasChangesInRange(startLine: number, endLine: number, changedLines: Set<number>): boolean {\n for (let line = startLine; line <= endLine; line++) {\n if (changedLines.has(line)) {\n return true;\n }\n }\n return false;\n }\n\n /** True if a node (method/function) is newly added or has any changed line in its range. */\n isNewOrModified(\n name: string,\n startLine: number,\n endLine: number,\n changedLines: Set<number>,\n newMethodNames: Set<string>,\n ): boolean {\n if (newMethodNames.has(name)) return true;\n return this.hasChangesInRange(startLine, endLine, changedLines);\n }\n\n // A file is \"a test file\" (excluded from diff-scoped rules) when it is a .spec/.test file or lives\n // under a __tests__/ directory.\n private isTestFile(file: string): boolean {\n return file.includes('.spec.ts') || file.includes('.test.ts') || file.includes('__tests__/');\n }\n}\n\n// Temporary migration delegators to DiffScope — removed once consumers inject it.\nconst diffScopeSvc = new DiffScope();\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to DiffScope; removed once consumers inject it\nexport function detectBase(workspaceRoot: string): Promise<string | null> {\n return diffScopeSvc.detectBase(workspaceRoot);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to DiffScope; removed once consumers inject it\nexport function resolveBase(workspaceRoot: string): Promise<DiffRange> {\n return diffScopeSvc.resolveBase(workspaceRoot);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to DiffScope; removed once consumers inject it\nexport function getChangedFiles(workspaceRoot: string, base: string, head?: string, opts?: ChangedFilesOptions): Promise<string[]> {\n return diffScopeSvc.getChangedFiles(workspaceRoot, base, head, opts);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to DiffScope; removed once consumers inject it\nexport function getFileDiff(workspaceRoot: string, file: string, base: string, head?: string): Promise<string> {\n return diffScopeSvc.getFileDiff(workspaceRoot, file, base, head);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to DiffScope; removed once consumers inject it\nexport function getChangedLineNumbers(diffContent: string): Set<number> {\n return diffScopeSvc.getChangedLineNumbers(diffContent);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to DiffScope; removed once consumers inject it\nexport function findNewMethodSignaturesInDiff(diffContent: string): Set<string> {\n return diffScopeSvc.findNewMethodSignaturesInDiff(diffContent);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to DiffScope; removed once consumers inject it\nexport function hasChangesInRange(startLine: number, endLine: number, changedLines: Set<number>): boolean {\n return diffScopeSvc.hasChangesInRange(startLine, endLine, changedLines);\n}\n\n// webpieces-disable no-function-outside-class -- temporary back-compat delegator to DiffScope; removed once consumers inject it\nexport function isNewOrModified(\n name: string,\n startLine: number,\n endLine: number,\n changedLines: Set<number>,\n newMethodNames: Set<string>,\n): boolean {\n return diffScopeSvc.isNewOrModified(name, startLine, endLine, changedLines, newMethodNames);\n}\n"]}
@@ -34,11 +34,11 @@ export declare class ConfigLoader {
34
34
  * `wp-ci`, which is the PR gate's build command and CI's. Its refusal (UntrackedPolicyError and the
35
35
  * gitignored-policy ConfigRepairError) and their cures are unchanged.
36
36
  */
37
- assertPolicyTracked(cwd: string): void;
37
+ assertPolicyTracked(cwd: string): Promise<void>;
38
38
  private loaded;
39
39
  private empty;
40
40
  }
41
41
  /** Public function entry point and injected service use the same implementation. */
42
42
  export declare function loadAndValidate(cwd: string): LoadedConfig;
43
43
  /** The gate-time policy-tracking check — see ConfigLoader.assertPolicyTracked. */
44
- export declare function assertPolicyTracked(cwd: string): void;
44
+ export declare function assertPolicyTracked(cwd: string): Promise<void>;
@@ -89,12 +89,12 @@ let ConfigLoader = class ConfigLoader {
89
89
  * `wp-ci`, which is the PR gate's build command and CI's. Its refusal (UntrackedPolicyError and the
90
90
  * gitignored-policy ConfigRepairError) and their cures are unchanged.
91
91
  */
92
- assertPolicyTracked(cwd) {
92
+ async assertPolicyTracked(cwd) {
93
93
  const configPath = this.configFile.findConfigFile(cwd);
94
94
  if (!configPath)
95
95
  return;
96
96
  const raw = this.configFile.readRawConfig(configPath), root = path.dirname(configPath);
97
- new policy_tracking_1.PolicyTracking().check(root, this.files.declarations(raw.rulePacks, root));
97
+ await new policy_tracking_1.PolicyTracking().check(root, this.files.declarations(raw.rulePacks, root));
98
98
  }
99
99
  loaded(configPath,
100
100
  // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
@@ -129,6 +129,6 @@ function loadAndValidate(cwd) {
129
129
  /** The gate-time policy-tracking check — see ConfigLoader.assertPolicyTracked. */
130
130
  // webpieces-disable no-function-outside-class -- the public function twin of loadAndValidate, for the wp-ci bin
131
131
  function assertPolicyTracked(cwd) {
132
- configLoaderSvc.assertPolicyTracked(cwd);
132
+ return configLoaderSvc.assertPolicyTracked(cwd);
133
133
  }
134
134
  //# sourceMappingURL=load-config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"load-config.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/load-config.ts"],"names":[],"mappings":";;;AAuJA,0CAEC;AAID,kDAEC;;AA/JD,wDAAkC;AAClC,yCAA2D;AAC3D,oDAAoD;AACpD,8DAA6D;AAC7D,uDAAwE;AACxE,+CAA2C;AAC3C,6DAAwD;AACxD,2DAA6E;AAC7E,6DAAoD;AAEpD,mCAA6D;AAC7D,+EAAwE;AACxE,yDAA0D;AAC1D,uDAAoF;AAEpF,iEAA8D;AAC9D,uDAAmD;AACnD,+DAAiE;AACjE,+DAAgH;AAChH,mDAAgD;AAChD,+DAA0D;AAC1D,2CAAoD;AAEpD,6GAA6G;AAC7G,MAAa,YAAY;IAGR;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IAVb,yDAAyD;IACzD,YACa,QAAwB,EACxB,WAAiC,EACjC,QAAwB,EACxB,MAAoB,EACpB,YAA0B,EAC1B,UAAsC,EACtC,UAAyB,EACzB,YAA8B,EAC9B,WAAyC;QARzC,aAAQ,GAAR,QAAQ,CAAgB;QACxB,gBAAW,GAAX,WAAW,CAAsB;QACjC,aAAQ,GAAR,QAAQ,CAAgB;QACxB,WAAM,GAAN,MAAM,CAAc;QACpB,iBAAY,GAAZ,YAAY,CAAc;QAC1B,eAAU,GAAV,UAAU,CAA4B;QACtC,eAAU,GAAV,UAAU,CAAe;QACzB,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,gBAAW,GAAX,WAAW,CAA8B;IACnD,CAAC;CACP;AAbD,oCAaC;AAGM,IAAM,YAAY,GAAlB,MAAM,YAAY;IAEA;IACA;IAFrB,YACqB,UAAsB,EACtB,KAAsB;QADt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,CAAC,GAAW;IACvC,OAAO,eAAe,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;AAChD,CAAC;AAED,kFAAkF;AAClF,gHAAgH;AAChH,SAAgB,mBAAmB,CAAC,GAAW;IAC3C,eAAe,CAAC,mBAAmB,CAAC,GAAG,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import * as path from 'node:path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ConfigObject } from '@webpieces/rules-sdk';\nimport { RepositoryLayout } from '@webpieces/tooling-common';\nimport { buildCommandsConfig, CommandsConfig } from './commands-config';\nimport { ConfigFile } from './config-file';\nimport { RulePackRegistry } from './rule-pack-registry';\nimport { PackPolicyFiles, PackPolicyFilesResult } from './pack-policy-files';\nimport { ExcludePaths } from './exclude-hook-paths';\nimport { PrGateConfig } from './pr-gate-config';\nimport { ResolvedConfig, ResolvedRuleConfig } from './types';\nimport { validateCommandsSection } from './commands-section-validators';\nimport { validateTopLevelKeys } from './config-key-rules';\nimport { validateExcludePaths, validateMatchRulesSection } from './validate-config';\nimport { MatchRuleConfig } from './match-rules-config';\nimport { WebpiecesRulesConfig } from './WebpiecesRulesConfig';\nimport { PolicyTracking } from './policy-tracking';\nimport { formatConfigErrorsBanner } from './config-error-banner';\nimport { ConfigRepairError, EditFileCure, RepositoryLayoutRepair, RunCommandCure } from './config-repair-error';\nimport { writeTemplate } from './load-template';\nimport { CONFIG_POLICY_DOC } from './config-error-banner';\nimport { PRUNE_UNKNOWN_COMMAND } from './constants';\n\n/** One root parse and one owner-resolution pass supply all consumers with the same registry and settings. */\nexport class LoadedConfig {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly resolved: ResolvedConfig,\n readonly rulesConfig: WebpiecesRulesConfig,\n readonly commands: CommandsConfig,\n readonly prGate: PrGateConfig,\n readonly excludePaths: ExcludePaths,\n readonly matchRules: readonly MatchRuleConfig[],\n readonly configPath: string | null,\n readonly ruleRegistry: RulePackRegistry,\n readonly policyFiles: PackPolicyFilesResult | null,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class ConfigLoader {\n constructor(\n private readonly configFile: ConfigFile,\n private readonly files: PackPolicyFiles,\n ) {}\n\n loadAndValidate(cwd: string): LoadedConfig {\n const configPath = this.configFile.findConfigFile(cwd);\n if (!configPath) return this.empty();\n const raw = this.configFile.readRawConfig(configPath),\n root = path.dirname(configPath);\n // webpieces-disable no-any-unknown -- the root parser returns opaque client JSON; these validators narrow every accepted field\n const document = raw as Record<string, unknown>;\n writeTemplate(root, CONFIG_POLICY_DOC);\n const errors = [\n ...validateTopLevelKeys(document),\n ...validateCommandsSection(raw.commands, document['pr-gate'], root),\n ...validateExcludePaths(raw.excludePaths),\n ...validateMatchRulesSection(raw['match-rules']),\n ];\n if (errors.length)\n throw new ConfigRepairError(formatConfigErrorsBanner(errors), [\n new EditFileCure(configPath, `Edit ${configPath} and apply every bullet above.`),\n new RunCommandCure(\n PRUNE_UNKNOWN_COMMAND,\n `${PRUNE_UNKNOWN_COMMAND} — deletes every key no validator has a schema for.`,\n ),\n ]);\n new RepositoryLayoutRepair().run(() => new RepositoryLayout().assertCurrent(root));\n const declarations = this.files.declarations(raw.rulePacks, root);\n const policy = this.files.resolve(root, this.files.select(root, declarations));\n return this.loaded(\n configPath,\n raw.commands,\n raw.excludePaths as string[],\n raw['match-rules'] as MatchRuleConfig[],\n policy,\n );\n }\n\n /**\n * \"Policy is shared through the git index\": every declared owner file is tracked and not ignored.\n *\n * NOT part of loadAndValidate (#1355). It is a COMMIT-TIME invariant — nothing about it changes\n * between two tool calls — and it costs two `git` processes, so running it on every config load put\n * it on the hottest path there is: every guard-hook invocation. It runs where work is SHARED instead:\n * `wp-ci`, which is the PR gate's build command and CI's. Its refusal (UntrackedPolicyError and the\n * gitignored-policy ConfigRepairError) and their cures are unchanged.\n */\n assertPolicyTracked(cwd: string): void {\n const configPath = this.configFile.findConfigFile(cwd);\n if (!configPath) return;\n const raw = this.configFile.readRawConfig(configPath),\n root = path.dirname(configPath);\n new PolicyTracking().check(root, this.files.declarations(raw.rulePacks, root));\n }\n\n private loaded(\n configPath: string,\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n commandsRaw: unknown,\n excluded: readonly string[],\n matches: readonly MatchRuleConfig[],\n policy: PackPolicyFilesResult,\n ): LoadedConfig {\n const commands = buildCommandsConfig(commandsRaw),\n values = new WebpiecesRulesConfig();\n const resolved = new Map<string, ResolvedRuleConfig>();\n for (const id of policy.registry.ruleIds()) {\n const explicit = policy.values[id];\n values[id] = explicit;\n const options = Object.assign(\n new ConfigObject(),\n policy.registry.optionalTuningFor(id),\n explicit,\n );\n resolved.set(id, new ResolvedRuleConfig(options));\n }\n return new LoadedConfig(\n new ResolvedConfig(resolved, new Set(policy.registry.ruleIds()), configPath),\n values,\n commands,\n commands.prGate,\n new ExcludePaths([...excluded]),\n matches,\n configPath,\n policy.registry,\n policy,\n );\n }\n\n private empty(): LoadedConfig {\n const commands = buildCommandsConfig(undefined);\n return new LoadedConfig(\n new ResolvedConfig(new Map(), new Set(), null),\n new WebpiecesRulesConfig(),\n commands,\n commands.prGate,\n new ExcludePaths([]),\n [],\n null,\n new RulePackRegistry([]),\n null,\n );\n }\n}\n\nconst configLoaderSvc = new ConfigLoader(new ConfigFile(), new PackPolicyFiles());\n\n/** Public function entry point and injected service use the same implementation. */\n// webpieces-disable no-function-outside-class -- canonical public loader function for CLI and executor entry points\nexport function loadAndValidate(cwd: string): LoadedConfig {\n return configLoaderSvc.loadAndValidate(cwd);\n}\n\n/** The gate-time policy-tracking check — see ConfigLoader.assertPolicyTracked. */\n// webpieces-disable no-function-outside-class -- the public function twin of loadAndValidate, for the wp-ci bin\nexport function assertPolicyTracked(cwd: string): void {\n configLoaderSvc.assertPolicyTracked(cwd);\n}\n"]}
1
+ {"version":3,"file":"load-config.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/load-config.ts"],"names":[],"mappings":";;;AAuJA,0CAEC;AAID,kDAEC;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C,QAAQ,EAAE,IAAI,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC,EAAE,UAAU,CAAC,EAC5E,MAAM,EACN,QAAQ,EACR,QAAQ,CAAC,MAAM,EACf,IAAI,iCAAY,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,EAC/B,OAAO,EACP,UAAU,EACV,MAAM,CAAC,QAAQ,EACf,MAAM,CACT,CAAC;IACN,CAAC;IAEO,KAAK;QACT,MAAM,QAAQ,GAAG,IAAA,qCAAmB,EAAC,SAAS,CAAC,CAAC;QAChD,OAAO,IAAI,YAAY,CACnB,IAAI,sBAAc,CAAC,IAAI,GAAG,EAAE,EAAE,IAAI,GAAG,EAAE,EAAE,IAAI,CAAC,EAC9C,IAAI,2CAAoB,EAAE,EAC1B,QAAQ,EACR,QAAQ,CAAC,MAAM,EACf,IAAI,iCAAY,CAAC,EAAE,CAAC,EACpB,EAAE,EACF,IAAI,EACJ,IAAI,qCAAgB,CAAC,EAAE,CAAC,EACxB,IAAI,CACP,CAAC;IACN,CAAC;CACJ,CAAA;AAzGY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAGJ,wBAAU;QACf,mCAAe;GAHlC,YAAY,CAyGxB;AAED,MAAM,eAAe,GAAG,IAAI,YAAY,CAAC,IAAI,wBAAU,EAAE,EAAE,IAAI,mCAAe,EAAE,CAAC,CAAC;AAElF,oFAAoF;AACpF,oHAAoH;AACpH,SAAgB,eAAe,CAAC,GAAW;IACvC,OAAO,eAAe,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;AAChD,CAAC;AAED,kFAAkF;AAClF,gHAAgH;AAChH,SAAgB,mBAAmB,CAAC,GAAW;IAC3C,OAAO,eAAe,CAAC,mBAAmB,CAAC,GAAG,CAAC,CAAC;AACpD,CAAC","sourcesContent":["import * as path from 'node:path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ConfigObject } from '@webpieces/rules-sdk';\nimport { RepositoryLayout } from '@webpieces/tooling-common';\nimport { buildCommandsConfig, CommandsConfig } from './commands-config';\nimport { ConfigFile } from './config-file';\nimport { RulePackRegistry } from './rule-pack-registry';\nimport { PackPolicyFiles, PackPolicyFilesResult } from './pack-policy-files';\nimport { ExcludePaths } from './exclude-hook-paths';\nimport { PrGateConfig } from './pr-gate-config';\nimport { ResolvedConfig, ResolvedRuleConfig } from './types';\nimport { validateCommandsSection } from './commands-section-validators';\nimport { validateTopLevelKeys } from './config-key-rules';\nimport { validateExcludePaths, validateMatchRulesSection } from './validate-config';\nimport { MatchRuleConfig } from './match-rules-config';\nimport { WebpiecesRulesConfig } from './WebpiecesRulesConfig';\nimport { PolicyTracking } from './policy-tracking';\nimport { formatConfigErrorsBanner } from './config-error-banner';\nimport { ConfigRepairError, EditFileCure, RepositoryLayoutRepair, RunCommandCure } from './config-repair-error';\nimport { writeTemplate } from './load-template';\nimport { CONFIG_POLICY_DOC } from './config-error-banner';\nimport { PRUNE_UNKNOWN_COMMAND } from './constants';\n\n/** One root parse and one owner-resolution pass supply all consumers with the same registry and settings. */\nexport class LoadedConfig {\n // eslint-disable-next-line @typescript-eslint/max-params\n constructor(\n readonly resolved: ResolvedConfig,\n readonly rulesConfig: WebpiecesRulesConfig,\n readonly commands: CommandsConfig,\n readonly prGate: PrGateConfig,\n readonly excludePaths: ExcludePaths,\n readonly matchRules: readonly MatchRuleConfig[],\n readonly configPath: string | null,\n readonly ruleRegistry: RulePackRegistry,\n readonly policyFiles: PackPolicyFilesResult | null,\n ) {}\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class ConfigLoader {\n constructor(\n private readonly configFile: ConfigFile,\n private readonly files: PackPolicyFiles,\n ) {}\n\n loadAndValidate(cwd: string): LoadedConfig {\n const configPath = this.configFile.findConfigFile(cwd);\n if (!configPath) return this.empty();\n const raw = this.configFile.readRawConfig(configPath),\n root = path.dirname(configPath);\n // webpieces-disable no-any-unknown -- the root parser returns opaque client JSON; these validators narrow every accepted field\n const document = raw as Record<string, unknown>;\n writeTemplate(root, CONFIG_POLICY_DOC);\n const errors = [\n ...validateTopLevelKeys(document),\n ...validateCommandsSection(raw.commands, document['pr-gate'], root),\n ...validateExcludePaths(raw.excludePaths),\n ...validateMatchRulesSection(raw['match-rules']),\n ];\n if (errors.length)\n throw new ConfigRepairError(formatConfigErrorsBanner(errors), [\n new EditFileCure(configPath, `Edit ${configPath} and apply every bullet above.`),\n new RunCommandCure(\n PRUNE_UNKNOWN_COMMAND,\n `${PRUNE_UNKNOWN_COMMAND} — deletes every key no validator has a schema for.`,\n ),\n ]);\n new RepositoryLayoutRepair().run(() => new RepositoryLayout().assertCurrent(root));\n const declarations = this.files.declarations(raw.rulePacks, root);\n const policy = this.files.resolve(root, this.files.select(root, declarations));\n return this.loaded(\n configPath,\n raw.commands,\n raw.excludePaths as string[],\n raw['match-rules'] as MatchRuleConfig[],\n policy,\n );\n }\n\n /**\n * \"Policy is shared through the git index\": every declared owner file is tracked and not ignored.\n *\n * NOT part of loadAndValidate (#1355). It is a COMMIT-TIME invariant — nothing about it changes\n * between two tool calls — and it costs two `git` processes, so running it on every config load put\n * it on the hottest path there is: every guard-hook invocation. It runs where work is SHARED instead:\n * `wp-ci`, which is the PR gate's build command and CI's. Its refusal (UntrackedPolicyError and the\n * gitignored-policy ConfigRepairError) and their cures are unchanged.\n */\n async assertPolicyTracked(cwd: string): Promise<void> {\n const configPath = this.configFile.findConfigFile(cwd);\n if (!configPath) return;\n const raw = this.configFile.readRawConfig(configPath),\n root = path.dirname(configPath);\n await new PolicyTracking().check(root, this.files.declarations(raw.rulePacks, root));\n }\n\n private loaded(\n configPath: string,\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n commandsRaw: unknown,\n excluded: readonly string[],\n matches: readonly MatchRuleConfig[],\n policy: PackPolicyFilesResult,\n ): LoadedConfig {\n const commands = buildCommandsConfig(commandsRaw),\n values = new WebpiecesRulesConfig();\n const resolved = new Map<string, ResolvedRuleConfig>();\n for (const id of policy.registry.ruleIds()) {\n const explicit = policy.values[id];\n values[id] = explicit;\n const options = Object.assign(\n new ConfigObject(),\n policy.registry.optionalTuningFor(id),\n explicit,\n );\n resolved.set(id, new ResolvedRuleConfig(options));\n }\n return new LoadedConfig(\n new ResolvedConfig(resolved, new Set(policy.registry.ruleIds()), configPath),\n values,\n commands,\n commands.prGate,\n new ExcludePaths([...excluded]),\n matches,\n configPath,\n policy.registry,\n policy,\n );\n }\n\n private empty(): LoadedConfig {\n const commands = buildCommandsConfig(undefined);\n return new LoadedConfig(\n new ResolvedConfig(new Map(), new Set(), null),\n new WebpiecesRulesConfig(),\n commands,\n commands.prGate,\n new ExcludePaths([]),\n [],\n null,\n new RulePackRegistry([]),\n null,\n );\n }\n}\n\nconst configLoaderSvc = new ConfigLoader(new ConfigFile(), new PackPolicyFiles());\n\n/** Public function entry point and injected service use the same implementation. */\n// webpieces-disable no-function-outside-class -- canonical public loader function for CLI and executor entry points\nexport function loadAndValidate(cwd: string): LoadedConfig {\n return configLoaderSvc.loadAndValidate(cwd);\n}\n\n/** The gate-time policy-tracking check — see ConfigLoader.assertPolicyTracked. */\n// webpieces-disable no-function-outside-class -- the public function twin of loadAndValidate, for the wp-ci bin\nexport function assertPolicyTracked(cwd: string): Promise<void> {\n return configLoaderSvc.assertPolicyTracked(cwd);\n}\n"]}
@@ -19,7 +19,7 @@ class MigrateDirsCli {
19
19
  new rule_pack_sync_1.RulePackSync(new config_file_1.ConfigFile(), new pack_policy_files_1.PackPolicyFiles(), new tooling_common_1.AtomicFile()).run(root);
20
20
  if (args.includes('--stage')) {
21
21
  const raw = new config_file_1.ConfigFile().readRawConfig(`${root}/webpieces.config.json`);
22
- new policy_tracking_1.PolicyTracking().stage(root, new pack_policy_files_1.PackPolicyFiles().declarations(raw.rulePacks, root));
22
+ await new policy_tracking_1.PolicyTracking().stage(root, new pack_policy_files_1.PackPolicyFiles().declarations(raw.rulePacks, root));
23
23
  }
24
24
  console.log(`Webpieces directories migrated. Review and commit .webpieces-config/ and webpieces.config.json; ignore only .webpieces/.\n${changed.join('\n')}`);
25
25
  }
@@ -1 +1 @@
1
- {"version":3,"file":"migrate-dirs-cli.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/migrate-dirs-cli.ts"],"names":[],"mappings":";;;;AACA,8DAAwF;AACxF,+CAA2C;AAC3C,2DAAsD;AACtD,qDAAgD;AAChD,uDAAmD;AACnD,2CAA6C;AAC7C,yCAAqC;AAErC,MAAa,cAAc;IACvB,KAAK,CAAC,IAAI;QACN,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACnC,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,KAAK,SAAS,CAAC;YAC/C,MAAM,IAAI,8BAAa,CACnB,kGAAkG,CACrG,CAAC;QACN,MAAM,IAAI,GAAG,IAAI,0BAAc,EAAE,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;QACjE,MAAM,OAAO,GAAG,IAAI,iCAAgB,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACrD,IAAI,6BAAY,CAAC,IAAI,wBAAU,EAAE,EAAE,IAAI,mCAAe,EAAE,EAAE,IAAI,2BAAU,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACtF,IAAI,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC;YAC3B,MAAM,GAAG,GAAG,IAAI,wBAAU,EAAE,CAAC,aAAa,CAAC,GAAG,IAAI,wBAAwB,CAAC,CAAC;YAC5E,IAAI,gCAAc,EAAE,CAAC,KAAK,CACtB,IAAI,EACJ,IAAI,mCAAe,EAAE,CAAC,YAAY,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,CAC1D,CAAC;QACN,CAAC;QACD,OAAO,CAAC,GAAG,CACP,6HAA6H,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CACpJ,CAAC;IACN,CAAC;CACJ;AArBD,wCAqBC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM;IAAE,IAAA,kBAAO,EAAC,GAAG,EAAE,CAAC,IAAI,cAAc,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { RepositoryLayout, AtomicFile, InformAiError } from '@webpieces/tooling-common';\nimport { ConfigFile } from './config-file';\nimport { PackPolicyFiles } from './pack-policy-files';\nimport { RulePackSync } from './rule-pack-sync';\nimport { PolicyTracking } from './policy-tracking';\nimport { RepoRootFinder } from './repo-root';\nimport { runMain } from './run-main';\n\nexport class MigrateDirsCli {\n async main(): Promise<void> {\n const args = process.argv.slice(2);\n if (args.some((argument) => argument !== '--stage'))\n throw new InformAiError(\n 'Usage: pnpm wp-migrate-dirs [--stage]. --stage explicitly stages the migrated policy for commit.',\n );\n const root = new RepoRootFinder().resolveRepoRoot(process.cwd());\n const changed = new RepositoryLayout().migrate(root);\n new RulePackSync(new ConfigFile(), new PackPolicyFiles(), new AtomicFile()).run(root);\n if (args.includes('--stage')) {\n const raw = new ConfigFile().readRawConfig(`${root}/webpieces.config.json`);\n new PolicyTracking().stage(\n root,\n new PackPolicyFiles().declarations(raw.rulePacks, root),\n );\n }\n console.log(\n `Webpieces directories migrated. Review and commit .webpieces-config/ and webpieces.config.json; ignore only .webpieces/.\\n${changed.join('\\n')}`,\n );\n }\n}\n\nif (require.main === module) runMain(() => new MigrateDirsCli().main());\n"]}
1
+ {"version":3,"file":"migrate-dirs-cli.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/migrate-dirs-cli.ts"],"names":[],"mappings":";;;;AACA,8DAAwF;AACxF,+CAA2C;AAC3C,2DAAsD;AACtD,qDAAgD;AAChD,uDAAmD;AACnD,2CAA6C;AAC7C,yCAAqC;AAErC,MAAa,cAAc;IACvB,KAAK,CAAC,IAAI;QACN,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACnC,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,KAAK,SAAS,CAAC;YAC/C,MAAM,IAAI,8BAAa,CACnB,kGAAkG,CACrG,CAAC;QACN,MAAM,IAAI,GAAG,IAAI,0BAAc,EAAE,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;QACjE,MAAM,OAAO,GAAG,IAAI,iCAAgB,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACrD,IAAI,6BAAY,CAAC,IAAI,wBAAU,EAAE,EAAE,IAAI,mCAAe,EAAE,EAAE,IAAI,2BAAU,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACtF,IAAI,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC;YAC3B,MAAM,GAAG,GAAG,IAAI,wBAAU,EAAE,CAAC,aAAa,CAAC,GAAG,IAAI,wBAAwB,CAAC,CAAC;YAC5E,MAAM,IAAI,gCAAc,EAAE,CAAC,KAAK,CAC5B,IAAI,EACJ,IAAI,mCAAe,EAAE,CAAC,YAAY,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,CAC1D,CAAC;QACN,CAAC;QACD,OAAO,CAAC,GAAG,CACP,6HAA6H,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CACpJ,CAAC;IACN,CAAC;CACJ;AArBD,wCAqBC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM;IAAE,IAAA,kBAAO,EAAC,GAAG,EAAE,CAAC,IAAI,cAAc,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { RepositoryLayout, AtomicFile, InformAiError } from '@webpieces/tooling-common';\nimport { ConfigFile } from './config-file';\nimport { PackPolicyFiles } from './pack-policy-files';\nimport { RulePackSync } from './rule-pack-sync';\nimport { PolicyTracking } from './policy-tracking';\nimport { RepoRootFinder } from './repo-root';\nimport { runMain } from './run-main';\n\nexport class MigrateDirsCli {\n async main(): Promise<void> {\n const args = process.argv.slice(2);\n if (args.some((argument) => argument !== '--stage'))\n throw new InformAiError(\n 'Usage: pnpm wp-migrate-dirs [--stage]. --stage explicitly stages the migrated policy for commit.',\n );\n const root = new RepoRootFinder().resolveRepoRoot(process.cwd());\n const changed = new RepositoryLayout().migrate(root);\n new RulePackSync(new ConfigFile(), new PackPolicyFiles(), new AtomicFile()).run(root);\n if (args.includes('--stage')) {\n const raw = new ConfigFile().readRawConfig(`${root}/webpieces.config.json`);\n await new PolicyTracking().stage(\n root,\n new PackPolicyFiles().declarations(raw.rulePacks, root),\n );\n }\n console.log(\n `Webpieces directories migrated. Review and commit .webpieces-config/ and webpieces.config.json; ignore only .webpieces/.\\n${changed.join('\\n')}`,\n );\n }\n}\n\nif (require.main === module) runMain(() => new MigrateDirsCli().main());\n"]}
@@ -1,3 +1,4 @@
1
+ import { GitProcessApi } from '@webpieces/tooling-common';
1
2
  /**
2
3
  * Finds ORPHAN DIRECTORIES — the package directories an `nx g move` leaves behind on every clone, which
3
4
  * git cannot remove and which then accumulate on every developer's machine forever.
@@ -32,12 +33,14 @@
32
33
  * to `.gitignore` makes the directory ignore-matched, which permanently protects it from this sweep.
33
34
  */
34
35
  export declare class OrphanDirScanner {
36
+ private readonly gitProcess;
37
+ constructor(gitProcess: GitProcessApi);
35
38
  /**
36
39
  * Every orphan directory under `repoRoot`, as repo-RELATIVE paths with no trailing slash. Empty when
37
40
  * the tree is clean, when `repoRoot` is not a git repository, or when git cannot be run at all — a
38
41
  * sweeper is never important enough to fail somebody's checkout over.
39
42
  */
40
- scan(repoRoot: string): OrphanCandidate[];
43
+ scan(repoRoot: string): Promise<OrphanCandidate[]>;
41
44
  /**
42
45
  * The DIRECTORY paths `git clean -Xdn` would remove, relative to `repoRoot` and slash-stripped.
43
46
  *
@@ -70,8 +73,8 @@ export declare class OrphanDirScanner {
70
73
  /**
71
74
  * `git <args>` in `repoRoot`, or null when git exits non-zero or could not be run at all.
72
75
  *
73
- * spawnSync rather than execFileSync because a non-zero exit is ORDINARY here — `check-ignore` says
74
- * "not ignored" that way — and a status code is a better answer to that question than an exception.
76
+ * A non-zero exit is ORDINARY here — `check-ignore` says "not ignored" that way — and the git edge
77
+ * reports it as a status code, never an exception.
75
78
  *
76
79
  * An ARGUMENT ARRAY, never a shell string: these paths come from a filesystem scan and may hold
77
80
  * spaces, quotes or `$`, and interpolating them into a shell would be building a command injection
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.OrphanCandidate = exports.OrphanDirScanner = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const path = tslib_1.__importStar(require("path"));
6
- const child_process_1 = require("child_process");
7
6
  const inversify_1 = require("inversify");
7
+ const tooling_common_1 = require("@webpieces/tooling-common");
8
8
  /**
9
9
  * Finds ORPHAN DIRECTORIES — the package directories an `nx g move` leaves behind on every clone, which
10
10
  * git cannot remove and which then accumulate on every developer's machine forever.
@@ -39,18 +39,22 @@ const inversify_1 = require("inversify");
39
39
  * to `.gitignore` makes the directory ignore-matched, which permanently protects it from this sweep.
40
40
  */
41
41
  let OrphanDirScanner = class OrphanDirScanner {
42
+ gitProcess;
43
+ constructor(gitProcess) {
44
+ this.gitProcess = gitProcess;
45
+ }
42
46
  /**
43
47
  * Every orphan directory under `repoRoot`, as repo-RELATIVE paths with no trailing slash. Empty when
44
48
  * the tree is clean, when `repoRoot` is not a git repository, or when git cannot be run at all — a
45
49
  * sweeper is never important enough to fail somebody's checkout over.
46
50
  */
47
- scan(repoRoot) {
48
- const reported = this.reportedByGitClean(repoRoot);
51
+ async scan(repoRoot) {
52
+ const reported = await this.reportedByGitClean(repoRoot);
49
53
  const candidates = [];
50
54
  for (const relative of reported) {
51
55
  if (!this.isSweepable(relative))
52
56
  continue;
53
- if (this.isIgnoredItself(repoRoot, relative))
57
+ if (await this.isIgnoredItself(repoRoot, relative))
54
58
  continue;
55
59
  candidates.push(new OrphanCandidate(relative, path.join(repoRoot, relative)));
56
60
  }
@@ -64,8 +68,8 @@ let OrphanDirScanner = class OrphanDirScanner {
64
68
  * are git telling us it found a nested repo — a linked worktree — which it refuses to descend into,
65
69
  * and so do we.
66
70
  */
67
- reportedByGitClean(repoRoot) {
68
- const raw = this.git(repoRoot, ['clean', '-Xdn']);
71
+ async reportedByGitClean(repoRoot) {
72
+ const raw = await this.git(repoRoot, ['clean', '-Xdn']);
69
73
  if (raw === null)
70
74
  return [];
71
75
  const paths = [];
@@ -86,8 +90,8 @@ let OrphanDirScanner = class OrphanDirScanner {
86
90
  * on no match, so a null answer here (any non-zero exit, including a git we could not run) means
87
91
  * "cannot confirm", and the directory is SPARED. Every uncertainty in this class resolves that way.
88
92
  */
89
- isIgnoredItself(repoRoot, relative) {
90
- return this.git(repoRoot, ['check-ignore', '-q', '--', relative]) !== null;
93
+ async isIgnoredItself(repoRoot, relative) {
94
+ return (await this.git(repoRoot, ['check-ignore', '-q', '--', relative])) !== null;
91
95
  }
92
96
  /**
93
97
  * The two structural exclusions, both about where a moved nx PROJECT can possibly live.
@@ -110,25 +114,24 @@ let OrphanDirScanner = class OrphanDirScanner {
110
114
  /**
111
115
  * `git <args>` in `repoRoot`, or null when git exits non-zero or could not be run at all.
112
116
  *
113
- * spawnSync rather than execFileSync because a non-zero exit is ORDINARY here — `check-ignore` says
114
- * "not ignored" that way — and a status code is a better answer to that question than an exception.
117
+ * A non-zero exit is ORDINARY here — `check-ignore` says "not ignored" that way — and the git edge
118
+ * reports it as a status code, never an exception.
115
119
  *
116
120
  * An ARGUMENT ARRAY, never a shell string: these paths come from a filesystem scan and may hold
117
121
  * spaces, quotes or `$`, and interpolating them into a shell would be building a command injection
118
122
  * into the one tool whose entire job is moving directories around.
119
123
  */
120
- git(repoRoot, args) {
121
- const result = (0, child_process_1.spawnSync)('git', ['-C', repoRoot, ...args], {
122
- encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: GIT_OUTPUT_LIMIT,
123
- });
124
- if (result.error !== undefined || result.status !== 0)
124
+ async git(repoRoot, args) {
125
+ const result = await this.gitProcess.run(['-C', repoRoot, ...args]);
126
+ if (!result.ok)
125
127
  return null;
126
128
  return result.stdout;
127
129
  }
128
130
  };
129
131
  exports.OrphanDirScanner = OrphanDirScanner;
130
132
  exports.OrphanDirScanner = OrphanDirScanner = tslib_1.__decorate([
131
- (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton)
133
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
134
+ tslib_1.__metadata("design:paramtypes", [tooling_common_1.GitProcessApi])
132
135
  ], OrphanDirScanner);
133
136
  /** One directory the sweep may archive. Data-only (per CLAUDE.md — classes, not interfaces, for data). */
134
137
  class OrphanCandidate {
@@ -145,6 +148,4 @@ exports.OrphanCandidate = OrphanCandidate;
145
148
  const WOULD_REMOVE = 'Would remove ';
146
149
  // `libraries/foo` is depth 2. Anything shallower is a top-level directory — see isSweepable().
147
150
  const MIN_DEPTH = 2;
148
- // `clean -Xdn` on a large monorepo prints a few hundred lines; 16MB is a ceiling no real repo approaches.
149
- const GIT_OUTPUT_LIMIT = 16 * 1024 * 1024;
150
151
  //# sourceMappingURL=orphan-dir-scan.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"orphan-dir-scan.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/orphan-dir-scan.ts"],"names":[],"mappings":";;;;AAAA,mDAA6B;AAC7B,iDAA0C;AAC1C,yCAA2D;AAE3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEI,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IACzB;;;;OAIG;IACH,IAAI,CAAC,QAAgB;QACjB,MAAM,QAAQ,GAAG,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC,CAAC;QACnD,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;IAErB,YAAY,YAAoB,EAAE,YAAoB;QAClD,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACrC,CAAC;CACJ;AAVD,0CAUC;AAED,MAAM,YAAY,GAAG,eAAe,CAAC;AACrC,+FAA+F;AAC/F,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,0GAA0G;AAC1G,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC","sourcesContent":["import * as path from 'path';\nimport { spawnSync } from 'child_process';\nimport { injectable, bindingScopeValues } from 'inversify';\n\n/**\n * Finds ORPHAN DIRECTORIES — the package directories an `nx g move` leaves behind on every clone, which\n * git cannot remove and which then accumulate on every developer's machine forever.\n *\n * ─── WHY GIT LEAVES THEM ──────────────────────────────────────────────────────────────────────────────\n * Git tracks files, not directories. When a move deletes every tracked file under `libraries/apis/foo/`,\n * git removes that directory ONLY if it is then truly empty — and it never is, because the build already\n * put an IGNORED `dist/` and `node_modules/` inside it. So the corpse stands, on every clone, and there\n * is no git setting that changes this (`core.pruneIgnoredDirs` does not exist).\n *\n * ─── WHY THE PREDICATE IS GIT'S OWN ANSWER AND NOT A HAND-ROLLED WALK ─────────────────────────────────\n * `git clean -Xdn` collapses a directory to a SINGLE entry exactly when everything beneath it is ignored,\n * and it does that using the repo's real ignore engine — nested `.gitignore` files, `!` negations and\n * all. Re-implementing that is how a sweeper ends up disagreeing with git about what is disposable.\n *\n * It also hands us the safety property for free, which is the reason this can run unattended: a directory\n * holding even ONE untracked-but-not-ignored file is NOT reported, so a developer's uncommitted new\n * package can never be a candidate. We do not check that ourselves; git's own output already encodes it.\n *\n * ─── THE ONE DISCRIMINATOR THAT NEEDS NO NAME LIST ────────────────────────────────────────────────────\n * `clean -Xdn` reports two very different things the same way:\n *\n * libraries/apis/pg-dataaccess-api/ ← a corpse: nothing tracked survives under it\n * libraries/apis/live-api/dist/ ← a LIVE project's build output, there on purpose\n *\n * They are separated by asking whether the directory ITSELF matches an ignore rule. `dist/` does\n * (`.gitignore:19:dist/`); `pg-dataaccess-api` does not, which is precisely the statement that this\n * directory was MEANT to hold tracked files — and none are left. No list of artifact directory names is\n * needed, and none is maintained, so the rule adapts to whatever any given consumer repo ignores.\n *\n * That also yields the opt-out, and it is one a developer would reach for anyway: adding `my-sandbox/`\n * to `.gitignore` makes the directory ignore-matched, which permanently protects it from this sweep.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class OrphanDirScanner {\n /**\n * Every orphan directory under `repoRoot`, as repo-RELATIVE paths with no trailing slash. Empty when\n * the tree is clean, when `repoRoot` is not a git repository, or when git cannot be run at all — a\n * sweeper is never important enough to fail somebody's checkout over.\n */\n scan(repoRoot: string): OrphanCandidate[] {\n const reported = this.reportedByGitClean(repoRoot);\n const candidates: OrphanCandidate[] = [];\n for (const relative of reported) {\n if (!this.isSweepable(relative)) continue;\n if (this.isIgnoredItself(repoRoot, relative)) continue;\n candidates.push(new OrphanCandidate(relative, path.join(repoRoot, relative)));\n }\n return candidates.sort((left: OrphanCandidate, right: OrphanCandidate): number =>\n left.relativePath.localeCompare(right.relativePath));\n }\n\n /**\n * The DIRECTORY paths `git clean -Xdn` would remove, relative to `repoRoot` and slash-stripped.\n *\n * Only entries ending in `/` are directories; a bare path is a single ignored FILE (`.env`,\n * `.claude/settings.local.json`) and is none of this sweep's business. `Would skip repository` lines\n * are git telling us it found a nested repo — a linked worktree — which it refuses to descend into,\n * and so do we.\n */\n private reportedByGitClean(repoRoot: string): string[] {\n const raw = this.git(repoRoot, ['clean', '-Xdn']);\n if (raw === null) return [];\n const paths: string[] = [];\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(WOULD_REMOVE)) continue;\n const target = trimmed.slice(WOULD_REMOVE.length).trim();\n if (!target.endsWith('/')) continue;\n paths.push(target.slice(0, -1));\n }\n return paths;\n }\n\n /**\n * True when git matches an ignore rule against the DIRECTORY ITSELF — i.e. it is a build artifact\n * somebody declared disposable-but-expected, not a corpse. `check-ignore -q` exits 0 on a match and 1\n * on no match, so a null answer here (any non-zero exit, including a git we could not run) means\n * \"cannot confirm\", and the directory is SPARED. Every uncertainty in this class resolves that way.\n */\n private isIgnoredItself(repoRoot: string, relative: string): boolean {\n return this.git(repoRoot, ['check-ignore', '-q', '--', relative]) !== null;\n }\n\n /**\n * The two structural exclusions, both about where a moved nx PROJECT can possibly live.\n *\n * DOT SEGMENTS: `.nx/`, `.idea/`, `.webpieces/` and friends are reported whole by `clean -Xdn` (their\n * contents are ignored, the directories themselves are not) and would otherwise pass the discriminator\n * above perfectly. They are tool state, they are supposed to be there, and no nx project is named with\n * a leading dot. Excluding the whole class by shape beats naming today's four and meeting a fifth.\n *\n * DEPTH: a moved project lives at `libraries/x`, `apps/x`, `packages/y/z` — never at the top level.\n * Requiring depth >= 2 costs nothing real and takes every top-level directory in the repo permanently\n * out of reach of an automated `mv`.\n */\n private isSweepable(relative: string): boolean {\n const segments = relative.split('/');\n if (segments.length < MIN_DEPTH) return false;\n return !segments.some((segment: string): boolean => segment.startsWith('.'));\n }\n\n /**\n * `git <args>` in `repoRoot`, or null when git exits non-zero or could not be run at all.\n *\n * spawnSync rather than execFileSync because a non-zero exit is ORDINARY here — `check-ignore` says\n * \"not ignored\" that way — and a status code is a better answer to that question than an exception.\n *\n * An ARGUMENT ARRAY, never a shell string: these paths come from a filesystem scan and may hold\n * spaces, quotes or `$`, and interpolating them into a shell would be building a command injection\n * into the one tool whose entire job is moving directories around.\n */\n private git(repoRoot: string, args: string[]): string | null {\n const result = spawnSync('git', ['-C', repoRoot, ...args], {\n encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: GIT_OUTPUT_LIMIT,\n });\n if (result.error !== undefined || result.status !== 0) return null;\n return result.stdout;\n }\n}\n\n/** One directory the sweep may archive. Data-only (per CLAUDE.md — classes, not interfaces, for data). */\nexport class OrphanCandidate {\n /** Repo-relative, no trailing slash — e.g. `libraries/apis/pg-dataaccess-api`. */\n relativePath: string;\n /** The same directory as an absolute path, which is what any `mv` needs. */\n absolutePath: string;\n\n constructor(relativePath: string, absolutePath: string) {\n this.relativePath = relativePath;\n this.absolutePath = absolutePath;\n }\n}\n\nconst WOULD_REMOVE = 'Would remove ';\n// `libraries/foo` is depth 2. Anything shallower is a top-level directory — see isSweepable().\nconst MIN_DEPTH = 2;\n// `clean -Xdn` on a large monorepo prints a few hundred lines; 16MB is a ceiling no real repo approaches.\nconst GIT_OUTPUT_LIMIT = 16 * 1024 * 1024;\n"]}
1
+ {"version":3,"file":"orphan-dir-scan.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/orphan-dir-scan.ts"],"names":[],"mappings":";;;;AAAA,mDAA6B;AAC7B,yCAA2D;AAC3D,8DAA0D;AAE1D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEI,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IACI;IAA7B,YAA6B,UAAyB;QAAzB,eAAU,GAAV,UAAU,CAAe;IAAG,CAAC;IAE1D;;;;OAIG;IACH,KAAK,CAAC,IAAI,CAAC,QAAgB;QACvB,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC,CAAC;QACzD,MAAM,UAAU,GAAsB,EAAE,CAAC;QACzC,KAAK,MAAM,QAAQ,IAAI,QAAQ,EAAE,CAAC;YAC9B,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC;gBAAE,SAAS;YAC1C,IAAI,MAAM,IAAI,CAAC,eAAe,CAAC,QAAQ,EAAE,QAAQ,CAAC;gBAAE,SAAS;YAC7D,UAAU,CAAC,IAAI,CAAC,IAAI,eAAe,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;QAClF,CAAC;QACD,OAAO,UAAU,CAAC,IAAI,CAAC,CAAC,IAAqB,EAAE,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,QAAQ,CAAC,MAAM,GAAG,SAAS;YAAE,OAAO,KAAK,CAAC;QAC9C,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAe,EAAW,EAAE,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC;IACjF,CAAC;IAED;;;;;;;;;OASG;IACK,KAAK,CAAC,GAAG,CAAC,QAAgB,EAAE,IAAc;QAC9C,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC;QACpE,IAAI,CAAC,MAAM,CAAC,EAAE;YAAE,OAAO,IAAI,CAAC;QAC5B,OAAO,MAAM,CAAC,MAAM,CAAC;IACzB,CAAC;CACJ,CAAA;AArFY,4CAAgB;2BAAhB,gBAAgB;IAD5B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEI,8BAAa;GAD7C,gBAAgB,CAqF5B;AAED,0GAA0G;AAC1G,MAAa,eAAe;IACxB,kFAAkF;IAClF,YAAY,CAAS;IACrB,4EAA4E;IAC5E,YAAY,CAAS;IAErB,YAAY,YAAoB,EAAE,YAAoB;QAClD,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACrC,CAAC;CACJ;AAVD,0CAUC;AAED,MAAM,YAAY,GAAG,eAAe,CAAC;AACrC,+FAA+F;AAC/F,MAAM,SAAS,GAAG,CAAC,CAAC","sourcesContent":["import * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GitProcessApi } from '@webpieces/tooling-common';\n\n/**\n * Finds ORPHAN DIRECTORIES — the package directories an `nx g move` leaves behind on every clone, which\n * git cannot remove and which then accumulate on every developer's machine forever.\n *\n * ─── WHY GIT LEAVES THEM ──────────────────────────────────────────────────────────────────────────────\n * Git tracks files, not directories. When a move deletes every tracked file under `libraries/apis/foo/`,\n * git removes that directory ONLY if it is then truly empty — and it never is, because the build already\n * put an IGNORED `dist/` and `node_modules/` inside it. So the corpse stands, on every clone, and there\n * is no git setting that changes this (`core.pruneIgnoredDirs` does not exist).\n *\n * ─── WHY THE PREDICATE IS GIT'S OWN ANSWER AND NOT A HAND-ROLLED WALK ─────────────────────────────────\n * `git clean -Xdn` collapses a directory to a SINGLE entry exactly when everything beneath it is ignored,\n * and it does that using the repo's real ignore engine — nested `.gitignore` files, `!` negations and\n * all. Re-implementing that is how a sweeper ends up disagreeing with git about what is disposable.\n *\n * It also hands us the safety property for free, which is the reason this can run unattended: a directory\n * holding even ONE untracked-but-not-ignored file is NOT reported, so a developer's uncommitted new\n * package can never be a candidate. We do not check that ourselves; git's own output already encodes it.\n *\n * ─── THE ONE DISCRIMINATOR THAT NEEDS NO NAME LIST ────────────────────────────────────────────────────\n * `clean -Xdn` reports two very different things the same way:\n *\n * libraries/apis/pg-dataaccess-api/ ← a corpse: nothing tracked survives under it\n * libraries/apis/live-api/dist/ ← a LIVE project's build output, there on purpose\n *\n * They are separated by asking whether the directory ITSELF matches an ignore rule. `dist/` does\n * (`.gitignore:19:dist/`); `pg-dataaccess-api` does not, which is precisely the statement that this\n * directory was MEANT to hold tracked files — and none are left. No list of artifact directory names is\n * needed, and none is maintained, so the rule adapts to whatever any given consumer repo ignores.\n *\n * That also yields the opt-out, and it is one a developer would reach for anyway: adding `my-sandbox/`\n * to `.gitignore` makes the directory ignore-matched, which permanently protects it from this sweep.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class OrphanDirScanner {\n constructor(private readonly gitProcess: GitProcessApi) {}\n\n /**\n * Every orphan directory under `repoRoot`, as repo-RELATIVE paths with no trailing slash. Empty when\n * the tree is clean, when `repoRoot` is not a git repository, or when git cannot be run at all — a\n * sweeper is never important enough to fail somebody's checkout over.\n */\n async scan(repoRoot: string): Promise<OrphanCandidate[]> {\n const reported = await this.reportedByGitClean(repoRoot);\n const candidates: OrphanCandidate[] = [];\n for (const relative of reported) {\n if (!this.isSweepable(relative)) continue;\n if (await this.isIgnoredItself(repoRoot, relative)) continue;\n candidates.push(new OrphanCandidate(relative, path.join(repoRoot, relative)));\n }\n return candidates.sort((left: OrphanCandidate, right: OrphanCandidate): number =>\n left.relativePath.localeCompare(right.relativePath));\n }\n\n /**\n * The DIRECTORY paths `git clean -Xdn` would remove, relative to `repoRoot` and slash-stripped.\n *\n * Only entries ending in `/` are directories; a bare path is a single ignored FILE (`.env`,\n * `.claude/settings.local.json`) and is none of this sweep's business. `Would skip repository` lines\n * are git telling us it found a nested repo — a linked worktree — which it refuses to descend into,\n * and so do we.\n */\n private async reportedByGitClean(repoRoot: string): Promise<string[]> {\n const raw = await this.git(repoRoot, ['clean', '-Xdn']);\n if (raw === null) return [];\n const paths: string[] = [];\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(WOULD_REMOVE)) continue;\n const target = trimmed.slice(WOULD_REMOVE.length).trim();\n if (!target.endsWith('/')) continue;\n paths.push(target.slice(0, -1));\n }\n return paths;\n }\n\n /**\n * True when git matches an ignore rule against the DIRECTORY ITSELF — i.e. it is a build artifact\n * somebody declared disposable-but-expected, not a corpse. `check-ignore -q` exits 0 on a match and 1\n * on no match, so a null answer here (any non-zero exit, including a git we could not run) means\n * \"cannot confirm\", and the directory is SPARED. Every uncertainty in this class resolves that way.\n */\n private async isIgnoredItself(repoRoot: string, relative: string): Promise<boolean> {\n return (await this.git(repoRoot, ['check-ignore', '-q', '--', relative])) !== null;\n }\n\n /**\n * The two structural exclusions, both about where a moved nx PROJECT can possibly live.\n *\n * DOT SEGMENTS: `.nx/`, `.idea/`, `.webpieces/` and friends are reported whole by `clean -Xdn` (their\n * contents are ignored, the directories themselves are not) and would otherwise pass the discriminator\n * above perfectly. They are tool state, they are supposed to be there, and no nx project is named with\n * a leading dot. Excluding the whole class by shape beats naming today's four and meeting a fifth.\n *\n * DEPTH: a moved project lives at `libraries/x`, `apps/x`, `packages/y/z` — never at the top level.\n * Requiring depth >= 2 costs nothing real and takes every top-level directory in the repo permanently\n * out of reach of an automated `mv`.\n */\n private isSweepable(relative: string): boolean {\n const segments = relative.split('/');\n if (segments.length < MIN_DEPTH) return false;\n return !segments.some((segment: string): boolean => segment.startsWith('.'));\n }\n\n /**\n * `git <args>` in `repoRoot`, or null when git exits non-zero or could not be run at all.\n *\n * A non-zero exit is ORDINARY here — `check-ignore` says \"not ignored\" that way — and the git edge\n * reports it as a status code, never an exception.\n *\n * An ARGUMENT ARRAY, never a shell string: these paths come from a filesystem scan and may hold\n * spaces, quotes or `$`, and interpolating them into a shell would be building a command injection\n * into the one tool whose entire job is moving directories around.\n */\n private async git(repoRoot: string, args: string[]): Promise<string | null> {\n const result = await this.gitProcess.run(['-C', repoRoot, ...args]);\n if (!result.ok) return null;\n return result.stdout;\n }\n}\n\n/** One directory the sweep may archive. Data-only (per CLAUDE.md — classes, not interfaces, for data). */\nexport class OrphanCandidate {\n /** Repo-relative, no trailing slash — e.g. `libraries/apis/pg-dataaccess-api`. */\n relativePath: string;\n /** The same directory as an absolute path, which is what any `mv` needs. */\n absolutePath: string;\n\n constructor(relativePath: string, absolutePath: string) {\n this.relativePath = relativePath;\n this.absolutePath = absolutePath;\n }\n}\n\nconst WOULD_REMOVE = 'Would remove ';\n// `libraries/foo` is depth 2. Anything shallower is a top-level directory — see isSweepable().\nconst MIN_DEPTH = 2;\n"]}
@@ -32,7 +32,7 @@ export declare class OrphanDirSweeper {
32
32
  * Scan `repoRoot`, and archive what was found when this machine has opted in. `now` is a parameter
33
33
  * so specs pin the sweep id rather than racing the clock.
34
34
  */
35
- sweep(repoRoot: string, now: Date): OrphanSweepReport;
35
+ sweep(repoRoot: string, now: Date): Promise<OrphanSweepReport>;
36
36
  }
37
37
  /**
38
38
  * What one sweep found and did, and how to say it out loud. Data-only apart from `render()`, which is
@@ -41,8 +41,8 @@ let OrphanDirSweeper = class OrphanDirSweeper {
41
41
  * Scan `repoRoot`, and archive what was found when this machine has opted in. `now` is a parameter
42
42
  * so specs pin the sweep id rather than racing the clock.
43
43
  */
44
- sweep(repoRoot, now) {
45
- const candidates = this.scanner.scan(repoRoot);
44
+ async sweep(repoRoot, now) {
45
+ const candidates = await this.scanner.scan(repoRoot);
46
46
  const enabled = this.homeConfigService.load().orphanDirSweep;
47
47
  if (candidates.length === 0)
48
48
  return new OrphanSweepReport(enabled, candidates, null, 0);
@@ -1 +1 @@
1
- {"version":3,"file":"orphan-dir-sweep.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/orphan-dir-sweep.ts"],"names":[],"mappings":";;;;AAAA,yCAA2D;AAE3D,uDAAsE;AACtE,6DAA0G;AAC1G,+CAAwG;AAExG;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEI,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IAEJ;IACA;IACA;IAHrB,YACqB,OAAyB,EACzB,QAA2B,EAC3B,iBAAoC;QAFpC,YAAO,GAAP,OAAO,CAAkB;QACzB,aAAQ,GAAR,QAAQ,CAAmB;QAC3B,sBAAiB,GAAjB,iBAAiB,CAAmB;IACtD,CAAC;IAEJ;;;OAGG;IACH,KAAK,CAAC,QAAgB,EAAE,GAAS;QAC7B,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC/C,MAAM,OAAO,GAAG,IAAI,CAAC,iBAAiB,CAAC,IAAI,EAAE,CAAC,cAAc,CAAC;QAC7D,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,IAAI,iBAAiB,CAAC,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QACxF,IAAI,CAAC,OAAO;YAAE,OAAO,IAAI,iBAAiB,CAAC,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QACvE,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,QAAQ,EAAE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,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC;IACzD,CAAC;IAED,qEAAqE;IACrE,OAAO;QACH,OAAO,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC;IAC1D,CAAC;CACJ;AA/ED,8CA+EC","sourcesContent":["import { injectable, bindingScopeValues } from 'inversify';\n\nimport { OrphanCandidate, OrphanDirScanner } from './orphan-dir-scan';\nimport { ArchivedOrphan, FailedOrphan, OrphanDirArchiver, OrphanSweepResult } from './orphan-dir-archive';\nimport { HOME_EXPERIMENTAL_SECTION, HOME_KEY_ORPHAN_DIR_SWEEP, HomeConfigService } from './home-config';\n\n/**\n * The orphan-directory sweep, end to end: find the corpses an `nx g move` left behind, and — only on a\n * machine that has explicitly opted in — archive them where they can be recovered.\n *\n * ─── WHY THE DEFAULT IS REPORT-ONLY ───────────────────────────────────────────────────────────────────\n * `experimental.orphan-dir-sweep` in `~/.webpieces/config.json` defaults to false, like every other key\n * in that optional, machine-local file. That gives the author of this feature exactly one thing nothing\n * else can: they can run it live across all of their own clones for a release, while every colleague\n * pulling the same version gets a report and an untouched working tree.\n *\n * The default direction is the whole safety argument, and it only points one way: absent means REPORT.\n * Nobody can discover this feature by finding their directories somewhere else — the machine has to say\n * `true` out loud first, and the key is greppable precisely because the permissive state is a token\n * rather than an absence.\n *\n * ─── WHY IT NEVER THROWS ──────────────────────────────────────────────────────────────────────────────\n * Every caller is a command whose real work is a checkout and a pull. Tidying is worth doing on the back\n * of that, and worth nothing at all if it can fail the thing it rode in on, so every failure below\n * resolves to a line of prose in the report. The one exception is deliberate: a MALFORMED\n * `~/.webpieces/config.json` propagates, because that file is the user's own instruction to this code and\n * silently ignoring a broken one is how a machine ends up in a state its owner did not choose.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class OrphanDirSweeper {\n constructor(\n private readonly scanner: OrphanDirScanner,\n private readonly archiver: OrphanDirArchiver,\n private readonly homeConfigService: HomeConfigService,\n ) {}\n\n /**\n * Scan `repoRoot`, and archive what was found when this machine has opted in. `now` is a parameter\n * so specs pin the sweep id rather than racing the clock.\n */\n sweep(repoRoot: string, now: Date): OrphanSweepReport {\n const candidates = this.scanner.scan(repoRoot);\n const enabled = this.homeConfigService.load().orphanDirSweep;\n if (candidates.length === 0) return new OrphanSweepReport(enabled, candidates, null, 0);\n if (!enabled) return new OrphanSweepReport(false, candidates, null, 0);\n const result = this.archiver.archive(repoRoot, candidates, now);\n return new OrphanSweepReport(true, candidates, result, this.archiver.reapAged(repoRoot, now));\n }\n}\n\n/**\n * What one sweep found and did, and how to say it out loud. Data-only apart from `render()`, which is\n * the report's own presentation of itself rather than business logic living somewhere else.\n */\nexport class OrphanSweepReport {\n /** Was archiving switched on for this machine? False means nothing on disk was touched. */\n enabled: boolean;\n /** Every orphan directory found, whether or not it was archived. */\n found: readonly OrphanCandidate[];\n /** The archive, or null when this was a report-only run or there was nothing to archive. */\n result: OrphanSweepResult | null;\n /** How many aged sweep directories were reaped from the trash on this run. */\n reapedSweeps: number;\n\n constructor(enabled: boolean, found: readonly OrphanCandidate[], result: OrphanSweepResult | null,\n reapedSweeps: number) {\n this.enabled = enabled;\n this.found = found;\n this.result = result;\n this.reapedSweeps = reapedSweeps;\n }\n\n /**\n * The human-facing block, or empty string when there is nothing to say. A clean tree prints NOTHING —\n * this rides along on somebody else's command, and a tidier that announces having found no work is a\n * tidier people start ignoring, and then stop reading the run where it did find some.\n */\n render(): string {\n if (this.found.length === 0) return '';\n if (!this.enabled) return this.renderReportOnly();\n return this.renderArchived();\n }\n\n /**\n * The opted-out form: name what was found, name the one edit that turns archiving on, and touch\n * nothing. It names the KEY rather than describing it, because the reader is usually an agent and the\n * mechanical edit is the only part of this it can act on.\n */\n private renderReportOnly(): string {\n return `${this.heading()}\\n`\n + ` Nothing was moved — archiving is off on this machine.\\n`\n + ` To archive them (never delete: they move to .webpieces/trash/<sweepId>/ with a recover=\\n`\n + ` command printed for each), add this key in ~/.webpieces/config.json — every key in that\\n`\n + ` file is optional, so this one line beside whatever is already there is the whole edit:\\n\\n`\n + ` { \"${HOME_EXPERIMENTAL_SECTION}\": { \"${HOME_KEY_ORPHAN_DIR_SWEEP}\": true } }\\n`;\n }\n\n private renderArchived(): string {\n const lines: string[] = [this.heading()];\n const result = this.result;\n if (result === null) return `${lines.join('\\n')}\\n`;\n lines.push(` archived to ${result.sweepDir}`);\n for (const moved of result.moved) {\n lines.push(` ${moved.relativePath}`);\n lines.push(` recover=${moved.recoverCommand}`);\n }\n for (const failure of result.failed) {\n lines.push(` SKIPPED ${failure.relativePath} — ${failure.reason}`);\n }\n if (result.manifestError !== null) {\n lines.push(` WARNING: the manifest could not be written — ${result.manifestError}`);\n lines.push(' The recover= lines above are the only copy. Save them before closing this terminal.');\n }\n if (this.reapedSweeps > 0) {\n lines.push(` reaped ${this.reapedSweeps} sweep(s) older than 30 days from the trash`);\n }\n return `${lines.join('\\n')}\\n`;\n }\n\n private heading(): string {\n const count = this.found.length;\n return `orphan directories (left by a project move; every file under them is git-ignored): ${count}`;\n }\n\n /** Everything archived on this run — empty on a report-only run. Convenience for callers and specs. */\n archived(): readonly ArchivedOrphan[] {\n return this.result === null ? [] : this.result.moved;\n }\n\n /** Everything found but not movable — empty on a report-only run. */\n skipped(): readonly FailedOrphan[] {\n return this.result === null ? [] : this.result.failed;\n }\n}\n"]}
1
+ {"version":3,"file":"orphan-dir-sweep.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/orphan-dir-sweep.ts"],"names":[],"mappings":";;;;AAAA,yCAA2D;AAE3D,uDAAsE;AACtE,6DAA0G;AAC1G,+CAAwG;AAExG;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEI,IAAM,gBAAgB,GAAtB,MAAM,gBAAgB;IAEJ;IACA;IACA;IAHrB,YACqB,OAAyB,EACzB,Q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KAAK,CAAC,IAAI,CAAC,eAAe,OAAO,CAAC,YAAY,MAAM,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QAC1E,CAAC;QACD,IAAI,MAAM,CAAC,aAAa,KAAK,IAAI,EAAE,CAAC;YAChC,KAAK,CAAC,IAAI,CAAC,kDAAkD,MAAM,CAAC,aAAa,EAAE,CAAC,CAAC;YACrF,KAAK,CAAC,IAAI,CAAC,uFAAuF,CAAC,CAAC;QACxG,CAAC;QACD,IAAI,IAAI,CAAC,YAAY,GAAG,CAAC,EAAE,CAAC;YACxB,KAAK,CAAC,IAAI,CAAC,YAAY,IAAI,CAAC,YAAY,6CAA6C,CAAC,CAAC;QAC3F,CAAC;QACD,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;IACnC,CAAC;IAEO,OAAO;QACX,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC;QAChC,OAAO,sFAAsF,KAAK,EAAE,CAAC;IACzG,CAAC;IAED,uGAAuG;IACvG,QAAQ;QACJ,OAAO,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC;IACzD,CAAC;IAED,qEAAqE;IACrE,OAAO;QACH,OAAO,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC;IAC1D,CAAC;CACJ;AA/ED,8CA+EC","sourcesContent":["import { injectable, bindingScopeValues } from 'inversify';\n\nimport { OrphanCandidate, OrphanDirScanner } from './orphan-dir-scan';\nimport { ArchivedOrphan, FailedOrphan, OrphanDirArchiver, OrphanSweepResult } from './orphan-dir-archive';\nimport { HOME_EXPERIMENTAL_SECTION, HOME_KEY_ORPHAN_DIR_SWEEP, HomeConfigService } from './home-config';\n\n/**\n * The orphan-directory sweep, end to end: find the corpses an `nx g move` left behind, and — only on a\n * machine that has explicitly opted in — archive them where they can be recovered.\n *\n * ─── WHY THE DEFAULT IS REPORT-ONLY ───────────────────────────────────────────────────────────────────\n * `experimental.orphan-dir-sweep` in `~/.webpieces/config.json` defaults to false, like every other key\n * in that optional, machine-local file. That gives the author of this feature exactly one thing nothing\n * else can: they can run it live across all of their own clones for a release, while every colleague\n * pulling the same version gets a report and an untouched working tree.\n *\n * The default direction is the whole safety argument, and it only points one way: absent means REPORT.\n * Nobody can discover this feature by finding their directories somewhere else — the machine has to say\n * `true` out loud first, and the key is greppable precisely because the permissive state is a token\n * rather than an absence.\n *\n * ─── WHY IT NEVER THROWS ──────────────────────────────────────────────────────────────────────────────\n * Every caller is a command whose real work is a checkout and a pull. Tidying is worth doing on the back\n * of that, and worth nothing at all if it can fail the thing it rode in on, so every failure below\n * resolves to a line of prose in the report. The one exception is deliberate: a MALFORMED\n * `~/.webpieces/config.json` propagates, because that file is the user's own instruction to this code and\n * silently ignoring a broken one is how a machine ends up in a state its owner did not choose.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class OrphanDirSweeper {\n constructor(\n private readonly scanner: OrphanDirScanner,\n private readonly archiver: OrphanDirArchiver,\n private readonly homeConfigService: HomeConfigService,\n ) {}\n\n /**\n * Scan `repoRoot`, and archive what was found when this machine has opted in. `now` is a parameter\n * so specs pin the sweep id rather than racing the clock.\n */\n async sweep(repoRoot: string, now: Date): Promise<OrphanSweepReport> {\n const candidates = await this.scanner.scan(repoRoot);\n const enabled = this.homeConfigService.load().orphanDirSweep;\n if (candidates.length === 0) return new OrphanSweepReport(enabled, candidates, null, 0);\n if (!enabled) return new OrphanSweepReport(false, candidates, null, 0);\n const result = this.archiver.archive(repoRoot, candidates, now);\n return new OrphanSweepReport(true, candidates, result, this.archiver.reapAged(repoRoot, now));\n }\n}\n\n/**\n * What one sweep found and did, and how to say it out loud. Data-only apart from `render()`, which is\n * the report's own presentation of itself rather than business logic living somewhere else.\n */\nexport class OrphanSweepReport {\n /** Was archiving switched on for this machine? False means nothing on disk was touched. */\n enabled: boolean;\n /** Every orphan directory found, whether or not it was archived. */\n found: readonly OrphanCandidate[];\n /** The archive, or null when this was a report-only run or there was nothing to archive. */\n result: OrphanSweepResult | null;\n /** How many aged sweep directories were reaped from the trash on this run. */\n reapedSweeps: number;\n\n constructor(enabled: boolean, found: readonly OrphanCandidate[], result: OrphanSweepResult | null,\n reapedSweeps: number) {\n this.enabled = enabled;\n this.found = found;\n this.result = result;\n this.reapedSweeps = reapedSweeps;\n }\n\n /**\n * The human-facing block, or empty string when there is nothing to say. A clean tree prints NOTHING —\n * this rides along on somebody else's command, and a tidier that announces having found no work is a\n * tidier people start ignoring, and then stop reading the run where it did find some.\n */\n render(): string {\n if (this.found.length === 0) return '';\n if (!this.enabled) return this.renderReportOnly();\n return this.renderArchived();\n }\n\n /**\n * The opted-out form: name what was found, name the one edit that turns archiving on, and touch\n * nothing. It names the KEY rather than describing it, because the reader is usually an agent and the\n * mechanical edit is the only part of this it can act on.\n */\n private renderReportOnly(): string {\n return `${this.heading()}\\n`\n + ` Nothing was moved — archiving is off on this machine.\\n`\n + ` To archive them (never delete: they move to .webpieces/trash/<sweepId>/ with a recover=\\n`\n + ` command printed for each), add this key in ~/.webpieces/config.json — every key in that\\n`\n + ` file is optional, so this one line beside whatever is already there is the whole edit:\\n\\n`\n + ` { \"${HOME_EXPERIMENTAL_SECTION}\": { \"${HOME_KEY_ORPHAN_DIR_SWEEP}\": true } }\\n`;\n }\n\n private renderArchived(): string {\n const lines: string[] = [this.heading()];\n const result = this.result;\n if (result === null) return `${lines.join('\\n')}\\n`;\n lines.push(` archived to ${result.sweepDir}`);\n for (const moved of result.moved) {\n lines.push(` ${moved.relativePath}`);\n lines.push(` recover=${moved.recoverCommand}`);\n }\n for (const failure of result.failed) {\n lines.push(` SKIPPED ${failure.relativePath} — ${failure.reason}`);\n }\n if (result.manifestError !== null) {\n lines.push(` WARNING: the manifest could not be written — ${result.manifestError}`);\n lines.push(' The recover= lines above are the only copy. Save them before closing this terminal.');\n }\n if (this.reapedSweeps > 0) {\n lines.push(` reaped ${this.reapedSweeps} sweep(s) older than 30 days from the trash`);\n }\n return `${lines.join('\\n')}\\n`;\n }\n\n private heading(): string {\n const count = this.found.length;\n return `orphan directories (left by a project move; every file under them is git-ignored): ${count}`;\n }\n\n /** Everything archived on this run — empty on a report-only run. Convenience for callers and specs. */\n archived(): readonly ArchivedOrphan[] {\n return this.result === null ? [] : this.result.moved;\n }\n\n /** Everything found but not movable — empty on a report-only run. */\n skipped(): readonly FailedOrphan[] {\n return this.result === null ? [] : this.result.failed;\n }\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import { GitProcessApi } from '@webpieces/tooling-common';
1
2
  import type { PackPolicyDeclaration } from './pack-policy-files';
2
3
  import { ConfigRepairError } from './config-repair-error';
3
4
  /**
@@ -16,8 +17,10 @@ export declare class UntrackedPolicyError extends ConfigRepairError {
16
17
  * invocation (#1355). `stage()` is wp-migrate-dirs' cure and is unchanged.
17
18
  */
18
19
  export declare class PolicyTracking {
19
- check(root: string, declarations: readonly PackPolicyDeclaration[]): void;
20
- stage(root: string, declarations: readonly PackPolicyDeclaration[]): void;
20
+ private readonly git;
21
+ constructor(git?: GitProcessApi);
22
+ check(root: string, declarations: readonly PackPolicyDeclaration[]): Promise<void>;
23
+ stage(root: string, declarations: readonly PackPolicyDeclaration[]): Promise<void>;
21
24
  /** Which of `files` git's index does not hold — each one named, never git's own pathspec advice. */
22
25
  private untracked;
23
26
  private files;
@@ -4,7 +4,7 @@ exports.PolicyTracking = exports.UntrackedPolicyError = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const fs = tslib_1.__importStar(require("node:fs"));
6
6
  const path = tslib_1.__importStar(require("node:path"));
7
- const node_child_process_1 = require("node:child_process");
7
+ const inversify_1 = require("inversify");
8
8
  const tooling_common_1 = require("@webpieces/tooling-common");
9
9
  const config_repair_error_1 = require("./config-repair-error");
10
10
  /** POSIX single-quoting for a path printed inside a command the reader will paste. */
@@ -41,33 +41,37 @@ exports.UntrackedPolicyError = UntrackedPolicyError;
41
41
  * it is a commit-time invariant that costs two `git` processes, and config load runs on every guard-hook
42
42
  * invocation (#1355). `stage()` is wp-migrate-dirs' cure and is unchanged.
43
43
  */
44
- class PolicyTracking {
45
- check(root, declarations) {
44
+ let PolicyTracking = class PolicyTracking {
45
+ git;
46
+ // Defaulted so the non-DI call sites (ConfigLoader, wp-migrate-dirs) can `new PolicyTracking()`, while
47
+ // inversify injects the container's git edge — which is what a feature test rebinds.
48
+ constructor(git = new tooling_common_1.GitProcessClient()) {
49
+ this.git = git;
50
+ }
51
+ async check(root, declarations) {
46
52
  // Standalone non-git schema validation is supported; CI and governed checkouts have .git.
47
53
  if (!fs.existsSync(path.join(root, '.git')))
48
54
  return;
49
55
  const files = this.files(root, declarations);
50
- const ignored = (0, node_child_process_1.spawnSync)('git', ['check-ignore', '--no-index', '--', ...files], {
51
- cwd: root,
52
- encoding: 'utf8',
53
- });
54
- if (ignored.status !== 0 && ignored.status !== 1)
56
+ // `check-ignore` exits 0 when something IS ignored and 1 when nothing is; anything else is a failure.
57
+ const ignored = await this.git.run(['check-ignore', '--no-index', '--', ...files], root);
58
+ if (ignored.code !== 0 && ignored.code !== 1)
55
59
  throw new tooling_common_1.InformAiError(`Cannot verify policy ignore status: ${ignored.stderr}. Repair git access, then retry.`);
56
60
  if (ignored.stdout.trim())
57
61
  throw new config_repair_error_1.ConfigRepairError(`Committed Webpieces policy is gitignored:\n${ignored.stdout}Only .webpieces/ belongs in .gitignore; .webpieces-config/ must be tracked.`, [
58
62
  new config_repair_error_1.EditFileCure(path.join(root, '.gitignore'), `Delete the .gitignore patterns that match the files listed above.`),
59
63
  ]);
60
- const untracked = this.untracked(root, files);
64
+ const untracked = await this.untracked(root, files);
61
65
  if (untracked.length)
62
66
  throw new UntrackedPolicyError(untracked);
63
67
  }
64
- stage(root, declarations) {
68
+ async stage(root, declarations) {
65
69
  // `.webpieces/` is the gitignored state directory, so `git add` refuses its paths. Untrack whatever
66
70
  // policy older releases committed there with `rm --cached`, which keeps every file on disk.
67
- const retired = (0, node_child_process_1.spawnSync)('git', ['rm', '-r', '-q', '--cached', '--ignore-unmatch', '--', '.webpieces'], { cwd: root, encoding: 'utf8' });
68
- if (retired.status !== 0)
71
+ const retired = await this.git.run(['rm', '-r', '-q', '--cached', '--ignore-unmatch', '--', '.webpieces'], root);
72
+ if (!retired.ok)
69
73
  throw new tooling_common_1.InformAiError(`Cannot untrack retired policy paths in .webpieces/: ${retired.stderr}. Verify git access before retrying.`);
70
- const result = (0, node_child_process_1.spawnSync)('git', [
74
+ const result = await this.git.run([
71
75
  '--literal-pathspecs',
72
76
  'add',
73
77
  '-A',
@@ -75,17 +79,14 @@ class PolicyTracking {
75
79
  'webpieces.config.json',
76
80
  '.gitignore',
77
81
  ...this.files(root, declarations),
78
- ], { cwd: root, encoding: 'utf8' });
79
- if (result.status !== 0)
82
+ ], root);
83
+ if (!result.ok)
80
84
  throw new tooling_common_1.InformAiError(`Could not stage Webpieces policy: ${result.stderr}. Remove policy ignore patterns and verify git access before retrying.`);
81
85
  }
82
86
  /** Which of `files` git's index does not hold — each one named, never git's own pathspec advice. */
83
- untracked(root, files) {
84
- const listed = (0, node_child_process_1.spawnSync)('git', ['--literal-pathspecs', 'ls-files', '-z', '--', ...files], {
85
- cwd: root,
86
- encoding: 'utf8',
87
- });
88
- if (listed.status !== 0)
87
+ async untracked(root, files) {
88
+ const listed = await this.git.run(['--literal-pathspecs', 'ls-files', '-z', '--', ...files], root);
89
+ if (!listed.ok)
89
90
  throw new tooling_common_1.InformAiError(`Cannot verify policy tracking status: ${listed.stderr}. Repair git access, then retry.`);
90
91
  const tracked = new Set(listed.stdout
91
92
  .split('\0')
@@ -102,6 +103,10 @@ class PolicyTracking {
102
103
  ])),
103
104
  ];
104
105
  }
105
- }
106
+ };
106
107
  exports.PolicyTracking = PolicyTracking;
108
+ exports.PolicyTracking = PolicyTracking = tslib_1.__decorate([
109
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
110
+ tslib_1.__metadata("design:paramtypes", [tooling_common_1.GitProcessApi])
111
+ ], PolicyTracking);
107
112
  //# sourceMappingURL=policy-tracking.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"policy-tracking.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/policy-tracking.ts"],"names":[],"mappings":";;;;AAAA,oDAA8B;AAC9B,wDAAkC;AAClC,2DAA+C;AAC/C,8DAAgF;AAEhF,+DAAwF;AAExF,sFAAsF;AACtF,MAAM,UAAU;IACZ,KAAK,CAAC,KAAa;QACf,OAAO,uBAAuB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC;IAC7F,CAAC;CACJ;AAED;;;GAGG;AACH,MAAa,oBAAqB,SAAQ,uCAAiB;IAC9C,SAAS,CAAoB;IAEtC,YAAY,SAA4B;QACpC,MAAM,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACvF,KAAK,CACD;YACI,iGAAiG;YACjG,+EAA+E;YAC/E,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC;SAClD,CAAC,IAAI,CAAC,IAAI,CAAC,EACZ;YACI,IAAI,oCAAc,CACd,cAAc,MAAM,EAAE,EACtB,cAAc,MAAM,qDAAqD,CAC5E;YACD,IAAI,oCAAc,CACd,GAAG,qCAAoB,UAAU,EACjC,GAAG,qCAAoB,oFAAoF,CAC9G;SACJ,CACJ,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;QACnC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a,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CACrD,CAAC;QACF,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9E,CAAC;IAEO,KAAK,CAAC,IAAY,EAAE,YAA8C;QACtE,MAAM,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QACvE,OAAO;YACH,GAAG,IAAI,GAAG,CACN,QAAQ,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC;gBAC3B,QAAQ;gBACR,IAAI,CAAC,QAAQ,CACT,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,EACrB,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,CAC7C;aACJ,CAAC,CACL;SACJ,CAAC;IACN,CAAC;CACJ;AA3FD,wCA2FC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { spawnSync } from 'node:child_process';\nimport { InformAiError, MIGRATE_DIRS_COMMAND } from '@webpieces/tooling-common';\nimport type { PackPolicyDeclaration } from './pack-policy-files';\nimport { ConfigRepairError, EditFileCure, RunCommandCure } from './config-repair-error';\n\n/** POSIX single-quoting for a path printed inside a command the reader will paste. */\nclass ShellQuote {\n quote(value: string): string {\n return /^[A-Za-z0-9_./@:+-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\\\''`)}'`;\n }\n}\n\n/**\n * Declared policy files git's index does not hold (#1327) — the PR gate's refusal (`wp-ci`), never a\n * config-load one (#1355): the guard hooks do not check tracking, so nothing blocks the `git add` cure.\n */\nexport class UntrackedPolicyError extends ConfigRepairError {\n readonly untracked: readonly string[];\n\n constructor(untracked: readonly string[]) {\n const quoted = untracked.map((file: string) => new ShellQuote().quote(file)).join(' ');\n super(\n [\n 'Webpieces policy files are not tracked by git. Policy is shared through the git index, so every',\n 'declared owner file must be staged and committed with your change. Untracked:',\n ...untracked.map((file: string) => ` ${file}`),\n ].join('\\n'),\n [\n new RunCommandCure(\n `git add -- ${quoted}`,\n `git add -- ${quoted} — stages exactly the untracked files listed above.`,\n ),\n new RunCommandCure(\n `${MIGRATE_DIRS_COMMAND} --stage`,\n `${MIGRATE_DIRS_COMMAND} --stage — stages webpieces.config.json, .gitignore and every declared owner file.`,\n ),\n ],\n );\n this.name = 'UntrackedPolicyError';\n this.untracked = untracked;\n }\n}\n\n/**\n * Git repositories must share policy through their index, including rules switched OFF.\n *\n * Checked at the PR gate and in CI (`wp-ci` → ConfigLoader.assertPolicyTracked), NOT on config load:\n * it is a commit-time invariant that costs two `git` processes, and config load runs on every guard-hook\n * invocation (#1355). `stage()` is wp-migrate-dirs' cure and is unchanged.\n */\nexport class PolicyTracking {\n check(root: string, declarations: readonly PackPolicyDeclaration[]): void {\n // Standalone non-git schema validation is supported; CI and governed checkouts have .git.\n if (!fs.existsSync(path.join(root, '.git'))) return;\n const files = this.files(root, declarations);\n const ignored = spawnSync('git', ['check-ignore', '--no-index', '--', ...files], {\n cwd: root,\n encoding: 'utf8',\n });\n if (ignored.status !== 0 && ignored.status !== 1)\n throw new InformAiError(\n `Cannot verify policy ignore status: ${ignored.stderr}. Repair git access, then retry.`,\n );\n if (ignored.stdout.trim())\n throw new ConfigRepairError(\n `Committed Webpieces policy is gitignored:\\n${ignored.stdout}Only .webpieces/ belongs in .gitignore; .webpieces-config/ must be tracked.`,\n [\n new EditFileCure(\n path.join(root, '.gitignore'),\n `Delete the .gitignore patterns that match the files listed above.`,\n ),\n ],\n );\n const untracked = this.untracked(root, files);\n if (untracked.length) throw new UntrackedPolicyError(untracked);\n }\n\n stage(root: string, declarations: readonly PackPolicyDeclaration[]): void {\n // `.webpieces/` is the gitignored state directory, so `git add` refuses its paths. Untrack whatever\n // policy older releases committed there with `rm --cached`, which keeps every file on disk.\n const retired = spawnSync(\n 'git',\n ['rm', '-r', '-q', '--cached', '--ignore-unmatch', '--', '.webpieces'],\n { cwd: root, encoding: 'utf8' },\n );\n if (retired.status !== 0)\n throw new InformAiError(\n `Cannot untrack retired policy paths in .webpieces/: ${retired.stderr}. Verify git access before retrying.`,\n );\n const result = spawnSync(\n 'git',\n [\n '--literal-pathspecs',\n 'add',\n '-A',\n '--',\n 'webpieces.config.json',\n '.gitignore',\n ...this.files(root, declarations),\n ],\n { cwd: root, encoding: 'utf8' },\n );\n if (result.status !== 0)\n throw new InformAiError(\n `Could not stage Webpieces policy: ${result.stderr}. Remove policy ignore patterns and verify git access before retrying.`,\n );\n }\n\n /** Which of `files` git's index does not hold — each one named, never git's own pathspec advice. */\n private untracked(root: string, files: readonly string[]): string[] {\n const listed = spawnSync('git', ['--literal-pathspecs', 'ls-files', '-z', '--', ...files], {\n cwd: root,\n encoding: 'utf8',\n });\n if (listed.status !== 0)\n throw new InformAiError(\n `Cannot verify policy tracking status: ${listed.stderr}. Repair git access, then retry.`,\n );\n const tracked = new Set(\n listed.stdout\n .split('\\0')\n .filter((entry: string) => entry !== '')\n .map((entry: string) => path.normalize(entry)),\n );\n return files.filter((file: string) => !tracked.has(path.normalize(file)));\n }\n\n private files(root: string, declarations: readonly PackPolicyDeclaration[]): string[] {\n const declared = declarations.map((declaration) => declaration.config);\n return [\n ...new Set(\n declared.flatMap((filename) => [\n filename,\n path.relative(\n fs.realpathSync(root),\n fs.realpathSync(path.join(root, filename)),\n ),\n ]),\n ),\n ];\n }\n}\n"]}
1
+ {"version":3,"file":"policy-tracking.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/policy-tracking.ts"],"names":[],"mappings":";;;;AAAA,oDAA8B;AAC9B,wDAAkC;AAClC,yCAA2D;AAC3D,8DAAiH;AAEjH,+DAAwF;AAExF,sFAAsF;AACtF,MAAM,UAAU;IACZ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,WAAW,CAAC,MAAM,CAAC,CAAC;QACvE,OAAO;YACH,GAAG,IAAI,GAAG,CACN,QAAQ,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC;gBAC3B,QAAQ;gBACR,IAAI,CAAC,QAAQ,CACT,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,EACrB,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,CAC7C;aACJ,CAAC,CACL;SACJ,CAAC;IACN,CAAC;CACJ,CAAA;AArFY,wCAAc;yBAAd,cAAc;IAD1B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIH,8BAAa;GAHtC,cAAc,CAqF1B","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { GitProcessApi, GitProcessClient, InformAiError, MIGRATE_DIRS_COMMAND } from '@webpieces/tooling-common';\nimport type { PackPolicyDeclaration } from './pack-policy-files';\nimport { ConfigRepairError, EditFileCure, RunCommandCure } from './config-repair-error';\n\n/** POSIX single-quoting for a path printed inside a command the reader will paste. */\nclass ShellQuote {\n quote(value: string): string {\n return /^[A-Za-z0-9_./@:+-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\\\''`)}'`;\n }\n}\n\n/**\n * Declared policy files git's index does not hold (#1327) — the PR gate's refusal (`wp-ci`), never a\n * config-load one (#1355): the guard hooks do not check tracking, so nothing blocks the `git add` cure.\n */\nexport class UntrackedPolicyError extends ConfigRepairError {\n readonly untracked: readonly string[];\n\n constructor(untracked: readonly string[]) {\n const quoted = untracked.map((file: string) => new ShellQuote().quote(file)).join(' ');\n super(\n [\n 'Webpieces policy files are not tracked by git. Policy is shared through the git index, so every',\n 'declared owner file must be staged and committed with your change. Untracked:',\n ...untracked.map((file: string) => ` ${file}`),\n ].join('\\n'),\n [\n new RunCommandCure(\n `git add -- ${quoted}`,\n `git add -- ${quoted} — stages exactly the untracked files listed above.`,\n ),\n new RunCommandCure(\n `${MIGRATE_DIRS_COMMAND} --stage`,\n `${MIGRATE_DIRS_COMMAND} --stage — stages webpieces.config.json, .gitignore and every declared owner file.`,\n ),\n ],\n );\n this.name = 'UntrackedPolicyError';\n this.untracked = untracked;\n }\n}\n\n/**\n * Git repositories must share policy through their index, including rules switched OFF.\n *\n * Checked at the PR gate and in CI (`wp-ci` → ConfigLoader.assertPolicyTracked), NOT on config load:\n * it is a commit-time invariant that costs two `git` processes, and config load runs on every guard-hook\n * invocation (#1355). `stage()` is wp-migrate-dirs' cure and is unchanged.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class PolicyTracking {\n // Defaulted so the non-DI call sites (ConfigLoader, wp-migrate-dirs) can `new PolicyTracking()`, while\n // inversify injects the container's git edge — which is what a feature test rebinds.\n constructor(private readonly git: GitProcessApi = new GitProcessClient()) {}\n\n async check(root: string, declarations: readonly PackPolicyDeclaration[]): Promise<void> {\n // Standalone non-git schema validation is supported; CI and governed checkouts have .git.\n if (!fs.existsSync(path.join(root, '.git'))) return;\n const files = this.files(root, declarations);\n // `check-ignore` exits 0 when something IS ignored and 1 when nothing is; anything else is a failure.\n const ignored = await this.git.run(['check-ignore', '--no-index', '--', ...files], root);\n if (ignored.code !== 0 && ignored.code !== 1)\n throw new InformAiError(\n `Cannot verify policy ignore status: ${ignored.stderr}. Repair git access, then retry.`,\n );\n if (ignored.stdout.trim())\n throw new ConfigRepairError(\n `Committed Webpieces policy is gitignored:\\n${ignored.stdout}Only .webpieces/ belongs in .gitignore; .webpieces-config/ must be tracked.`,\n [\n new EditFileCure(\n path.join(root, '.gitignore'),\n `Delete the .gitignore patterns that match the files listed above.`,\n ),\n ],\n );\n const untracked = await this.untracked(root, files);\n if (untracked.length) throw new UntrackedPolicyError(untracked);\n }\n\n async stage(root: string, declarations: readonly PackPolicyDeclaration[]): Promise<void> {\n // `.webpieces/` is the gitignored state directory, so `git add` refuses its paths. Untrack whatever\n // policy older releases committed there with `rm --cached`, which keeps every file on disk.\n const retired = await this.git.run(['rm', '-r', '-q', '--cached', '--ignore-unmatch', '--', '.webpieces'], root);\n if (!retired.ok)\n throw new InformAiError(\n `Cannot untrack retired policy paths in .webpieces/: ${retired.stderr}. Verify git access before retrying.`,\n );\n const result = await this.git.run(\n [\n '--literal-pathspecs',\n 'add',\n '-A',\n '--',\n 'webpieces.config.json',\n '.gitignore',\n ...this.files(root, declarations),\n ],\n root,\n );\n if (!result.ok)\n throw new InformAiError(\n `Could not stage Webpieces policy: ${result.stderr}. Remove policy ignore patterns and verify git access before retrying.`,\n );\n }\n\n /** Which of `files` git's index does not hold — each one named, never git's own pathspec advice. */\n private async untracked(root: string, files: readonly string[]): Promise<string[]> {\n const listed = await this.git.run(['--literal-pathspecs', 'ls-files', '-z', '--', ...files], root);\n if (!listed.ok)\n throw new InformAiError(\n `Cannot verify policy tracking status: ${listed.stderr}. Repair git access, then retry.`,\n );\n const tracked = new Set(\n listed.stdout\n .split('\\0')\n .filter((entry: string) => entry !== '')\n .map((entry: string) => path.normalize(entry)),\n );\n return files.filter((file: string) => !tracked.has(path.normalize(file)));\n }\n\n private files(root: string, declarations: readonly PackPolicyDeclaration[]): string[] {\n const declared = declarations.map((declaration) => declaration.config);\n return [\n ...new Set(\n declared.flatMap((filename) => [\n filename,\n path.relative(\n fs.realpathSync(root),\n fs.realpathSync(path.join(root, filename)),\n ),\n ]),\n ),\n ];\n }\n}\n"]}
package/src/run-main.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { ProcessExitApi } from '@webpieces/tooling-common';
1
2
  /**
2
3
  * The SINGLE sanctioned `process.exit` site for every CLI bin. Each bin's entry collapses to:
3
4
  *
@@ -10,5 +11,9 @@
10
11
  * This is what keeps a helper deep in the call tree from silently killing the whole process (the
11
12
  * `git-gatherInfo` → `merge-start` → `wp-start-upsert-pr` bug): control always unwinds to `main`,
12
13
  * and only here does the process actually exit. Enforced by `no-process-exit-outside-main`.
14
+ *
15
+ * The exit itself goes through the {@link ProcessExitApi} edge (#1381): every bin passes nothing and gets
16
+ * node's `process.exit`; a feature test passes `MockProcessExitApi` and runs a bin's whole top level in
17
+ * process, awaiting the returned promise instead of starting a node child to read an exit status.
13
18
  */
14
- export declare function runMain(main: () => Promise<void>): void;
19
+ export declare function runMain(main: () => Promise<void>, exit?: ProcessExitApi): Promise<void>;
package/src/run-main.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.runMain = runMain;
4
+ const tooling_common_1 = require("@webpieces/tooling-common");
4
5
  const cli_exit_error_1 = require("./cli-exit-error");
5
6
  const rule_fail_error_1 = require("./rule-fail-error");
6
7
  /**
@@ -15,15 +16,20 @@ const rule_fail_error_1 = require("./rule-fail-error");
15
16
  * This is what keeps a helper deep in the call tree from silently killing the whole process (the
16
17
  * `git-gatherInfo` → `merge-start` → `wp-start-upsert-pr` bug): control always unwinds to `main`,
17
18
  * and only here does the process actually exit. Enforced by `no-process-exit-outside-main`.
19
+ *
20
+ * The exit itself goes through the {@link ProcessExitApi} edge (#1381): every bin passes nothing and gets
21
+ * node's `process.exit`; a feature test passes `MockProcessExitApi` and runs a bin's whole top level in
22
+ * process, awaiting the returned promise instead of starting a node child to read an exit status.
18
23
  */
19
- function runMain(main) {
20
- // webpieces-disable no-any-unknown -- a promise rejection is genuinely of unknown type; narrowed below.
21
- main().catch((err) => {
24
+ // webpieces-disable no-function-outside-class -- the one sanctioned entry every bin calls as runMain(main); it changed only to take the exit edge (#1381)
25
+ function runMain(main, exit = new tooling_common_1.ProcessExitClient()) {
26
+ // webpieces-disable no-any-unknown, catch-must-propagate -- a rejection is genuinely of unknown type (narrowed below), and this IS the top-level handler: it renders the error for its audience and ends the process with its code
27
+ return main().catch((err) => {
22
28
  if (err instanceof cli_exit_error_1.CliExitError) {
23
29
  // A 0 exit is a success message (e.g. `--help`) → stdout; a non-zero abort → stderr.
24
30
  if (err.message)
25
31
  (err.exitCode === 0 ? process.stdout : process.stderr).write(err.message + '\n');
26
- process.exit(err.exitCode);
32
+ exit.exit(err.exitCode);
27
33
  }
28
34
  // A RULE refusal reaching a bin's top level goes through `renderRuleFailForHuman`, never through
29
35
  // a bare `err.message`: `message` is only the `aiMessage`, so printing it would SILENTLY DROP
@@ -35,7 +41,7 @@ function runMain(main) {
35
41
  ? (0, rule_fail_error_1.renderRuleFailForHuman)(err)
36
42
  : (err instanceof Error ? err.message : String(err));
37
43
  process.stderr.write(message + '\n');
38
- process.exit(1);
44
+ exit.exit(1);
39
45
  });
40
46
  }
41
47
  //# sourceMappingURL=run-main.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-main.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/run-main.ts"],"names":[],"mappings":";;AAgBA,0BAoBC;AApCD,qDAAgD;AAChD,uDAA0E;AAE1E;;;;;;;;;;;;GAYG;AACH,SAAgB,OAAO,CAAC,IAAyB;IAC7C,wGAAwG;IACxG,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAY,EAAE,EAAE;QAC1B,IAAI,GAAG,YAAY,6BAAY,EAAE,CAAC;YAC9B,qFAAqF;YACrF,IAAI,GAAG,CAAC,OAAO;gBAAE,CAAC,GAAG,CAAC,QAAQ,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;YAClG,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC/B,CAAC;QACD,iGAAiG;QACjG,8FAA8F;QAC9F,6FAA6F;QAC7F,8FAA8F;QAC9F,+FAA+F;QAC/F,wDAAwD;QACxD,MAAM,OAAO,GAAG,GAAG,YAAY,+BAAa;YACxC,CAAC,CAAC,IAAA,wCAAsB,EAAC,GAAG,CAAC;YAC7B,CAAC,CAAC,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;QACzD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;QACrC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import { CliExitError } from './cli-exit-error';\nimport { RuleFailError, renderRuleFailForHuman } from './rule-fail-error';\n\n/**\n * The SINGLE sanctioned `process.exit` site for every CLI bin. Each bin's entry collapses to:\n *\n * if (require.main === module) runMain(main);\n *\n * and `main` — plus every library function it calls — NEVER calls `process.exit` itself. Instead a\n * library that must abort throws `CliExitError(exitCode, message)`; this translator prints the\n * message and exits with that code. Any other thrown value is a real bug and exits 1.\n *\n * This is what keeps a helper deep in the call tree from silently killing the whole process (the\n * `git-gatherInfo` → `merge-start` → `wp-start-upsert-pr` bug): control always unwinds to `main`,\n * and only here does the process actually exit. Enforced by `no-process-exit-outside-main`.\n */\nexport function runMain(main: () => Promise<void>): void {\n // webpieces-disable no-any-unknown -- a promise rejection is genuinely of unknown type; narrowed below.\n main().catch((err: unknown) => {\n if (err instanceof CliExitError) {\n // A 0 exit is a success message (e.g. `--help`) → stdout; a non-zero abort → stderr.\n if (err.message) (err.exitCode === 0 ? process.stdout : process.stderr).write(err.message + '\\n');\n process.exit(err.exitCode);\n }\n // A RULE refusal reaching a bin's top level goes through `renderRuleFailForHuman`, never through\n // a bare `err.message`: `message` is only the `aiMessage`, so printing it would SILENTLY DROP\n // every `Option` the rule attached — the rule would have said exactly how to proceed and the\n // renderer would have thrown that away. Same \"one renderer per audience\" rule the ai-hook and\n // code-rules handlers already follow, and it is what lets a rule state its cures as `Option[]`\n // instead of hand-numbering them into a string literal.\n const message = err instanceof RuleFailError\n ? renderRuleFailForHuman(err)\n : (err instanceof Error ? err.message : String(err));\n process.stderr.write(message + '\\n');\n process.exit(1);\n });\n}\n"]}
1
+ {"version":3,"file":"run-main.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/run-main.ts"],"names":[],"mappings":";;AAuBA,0BAoBC;AA3CD,8DAA8E;AAE9E,qDAAgD;AAChD,uDAA0E;AAE1E;;;;;;;;;;;;;;;;GAgBG;AACH,0JAA0J;AAC1J,SAAgB,OAAO,CAAC,IAAyB,EAAE,OAAuB,IAAI,kCAAiB,EAAE;IAC7F,mOAAmO;IACnO,OAAO,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAY,EAAE,EAAE;QACjC,IAAI,GAAG,YAAY,6BAAY,EAAE,CAAC;YAC9B,qFAAqF;YACrF,IAAI,GAAG,CAAC,OAAO;gBAAE,CAAC,GAAG,CAAC,QAAQ,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;YAClG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC5B,CAAC;QACD,iGAAiG;QACjG,8FAA8F;QAC9F,6FAA6F;QAC7F,8FAA8F;QAC9F,+FAA+F;QAC/F,wDAAwD;QACxD,MAAM,OAAO,GAAG,GAAG,YAAY,+BAAa;YACxC,CAAC,CAAC,IAAA,wCAAsB,EAAC,GAAG,CAAC;YAC7B,CAAC,CAAC,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;QACzD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;QACrC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import { ProcessExitApi, ProcessExitClient } from '@webpieces/tooling-common';\n\nimport { CliExitError } from './cli-exit-error';\nimport { RuleFailError, renderRuleFailForHuman } from './rule-fail-error';\n\n/**\n * The SINGLE sanctioned `process.exit` site for every CLI bin. Each bin's entry collapses to:\n *\n * if (require.main === module) runMain(main);\n *\n * and `main` — plus every library function it calls — NEVER calls `process.exit` itself. Instead a\n * library that must abort throws `CliExitError(exitCode, message)`; this translator prints the\n * message and exits with that code. Any other thrown value is a real bug and exits 1.\n *\n * This is what keeps a helper deep in the call tree from silently killing the whole process (the\n * `git-gatherInfo` → `merge-start` → `wp-start-upsert-pr` bug): control always unwinds to `main`,\n * and only here does the process actually exit. Enforced by `no-process-exit-outside-main`.\n *\n * The exit itself goes through the {@link ProcessExitApi} edge (#1381): every bin passes nothing and gets\n * node's `process.exit`; a feature test passes `MockProcessExitApi` and runs a bin's whole top level in\n * process, awaiting the returned promise instead of starting a node child to read an exit status.\n */\n// webpieces-disable no-function-outside-class -- the one sanctioned entry every bin calls as runMain(main); it changed only to take the exit edge (#1381)\nexport function runMain(main: () => Promise<void>, exit: ProcessExitApi = new ProcessExitClient()): Promise<void> {\n // webpieces-disable no-any-unknown, catch-must-propagate -- a rejection is genuinely of unknown type (narrowed below), and this IS the top-level handler: it renders the error for its audience and ends the process with its code\n return main().catch((err: unknown) => {\n if (err instanceof CliExitError) {\n // A 0 exit is a success message (e.g. `--help`) → stdout; a non-zero abort → stderr.\n if (err.message) (err.exitCode === 0 ? process.stdout : process.stderr).write(err.message + '\\n');\n exit.exit(err.exitCode);\n }\n // A RULE refusal reaching a bin's top level goes through `renderRuleFailForHuman`, never through\n // a bare `err.message`: `message` is only the `aiMessage`, so printing it would SILENTLY DROP\n // every `Option` the rule attached — the rule would have said exactly how to proceed and the\n // renderer would have thrown that away. Same \"one renderer per audience\" rule the ai-hook and\n // code-rules handlers already follow, and it is what lets a rule state its cures as `Option[]`\n // instead of hand-numbering them into a string literal.\n const message = err instanceof RuleFailError\n ? renderRuleFailForHuman(err)\n : (err instanceof Error ? err.message : String(err));\n process.stderr.write(message + '\\n');\n exit.exit(1);\n });\n}\n"]}