@webpieces/rules-config 0.4.925 → 0.4.926
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 +5 -6
- package/src/config-file.js +4 -2
- package/src/config-file.js.map +1 -1
- package/src/config-key-rules.js +1 -1
- package/src/config-key-rules.js.map +1 -1
- package/src/config-repair-bootstrap-source.d.ts +1 -1
- package/src/config-repair-bootstrap-source.js +1 -1
- package/src/config-repair-bootstrap-source.js.map +1 -1
- package/src/config-repair-error.d.ts +46 -0
- package/src/config-repair-error.js +83 -0
- package/src/config-repair-error.js.map +1 -0
- package/src/config-repair-probe.d.ts +7 -1
- package/src/config-repair-probe.js +19 -29
- package/src/config-repair-probe.js.map +1 -1
- package/src/index.d.ts +2 -2
- package/src/index.js +7 -7
- package/src/index.js.map +1 -1
- package/src/legacy-config-upgrade.d.ts +1 -1
- package/src/legacy-config-upgrade.js +6 -6
- package/src/legacy-config-upgrade.js.map +1 -1
- package/src/load-config.d.ts +1 -3
- package/src/load-config.js +10 -10
- package/src/load-config.js.map +1 -1
- package/src/migrate-dirs-cli.js +1 -3
- package/src/migrate-dirs-cli.js.map +1 -1
- package/src/pack-policy-files.d.ts +10 -1
- package/src/pack-policy-files.js +97 -38
- package/src/pack-policy-files.js.map +1 -1
- package/src/policy-tracking.js +8 -8
- package/src/policy-tracking.js.map +1 -1
- package/src/rule-pack-sync.d.ts +8 -15
- package/src/rule-pack-sync.js +17 -137
- package/src/rule-pack-sync.js.map +1 -1
- package/templates/webpieces.guard-matrix.md +4 -5
- package/src/rule-pack-artifacts.d.ts +0 -23
- package/src/rule-pack-artifacts.js +0 -180
- package/src/rule-pack-artifacts.js.map +0 -1
- package/src/rules-sync-cli.d.ts +0 -7
- package/src/rules-sync-cli.js +0 -48
- package/src/rules-sync-cli.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/rules-config",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.926",
|
|
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.
|
|
23
|
-
"@webpieces/repo-workflow-core": "0.4.
|
|
24
|
-
"@webpieces/rules-sdk": "0.4.
|
|
22
|
+
"@webpieces/tooling-common": "0.4.926",
|
|
23
|
+
"@webpieces/repo-workflow-core": "0.4.926",
|
|
24
|
+
"@webpieces/rules-sdk": "0.4.926"
|
|
25
25
|
},
|
|
26
26
|
"author": "Dean Hiller",
|
|
27
27
|
"license": "Apache-2.0",
|
|
@@ -34,11 +34,10 @@
|
|
|
34
34
|
"access": "public"
|
|
35
35
|
},
|
|
36
36
|
"devDependencies": {
|
|
37
|
-
"@webpieces/tooling-testkit": "0.4.
|
|
37
|
+
"@webpieces/tooling-testkit": "0.4.926"
|
|
38
38
|
},
|
|
39
39
|
"types": "./src/index.d.ts",
|
|
40
40
|
"bin": {
|
|
41
|
-
"wp-rules-sync": "./src/rules-sync-cli.js",
|
|
42
41
|
"wp-migrate-dirs": "./src/migrate-dirs-cli.js"
|
|
43
42
|
}
|
|
44
43
|
}
|
package/src/config-file.js
CHANGED
|
@@ -7,8 +7,8 @@ const tslib_1 = require("tslib");
|
|
|
7
7
|
const fs = tslib_1.__importStar(require("fs"));
|
|
8
8
|
const path = tslib_1.__importStar(require("path"));
|
|
9
9
|
const inversify_1 = require("inversify");
|
|
10
|
-
const tooling_common_1 = require("@webpieces/tooling-common");
|
|
11
10
|
const to_error_1 = require("@webpieces/tooling-common/to-error");
|
|
11
|
+
const config_repair_error_1 = require("./config-repair-error");
|
|
12
12
|
exports.CONFIG_FILENAME = 'webpieces.config.json';
|
|
13
13
|
/**
|
|
14
14
|
* How many times a read+parse of webpieces.config.json is attempted before the failure is treated as
|
|
@@ -84,7 +84,9 @@ let ConfigFile = class ConfigFile {
|
|
|
84
84
|
return outcome.config;
|
|
85
85
|
lastError = outcome.error;
|
|
86
86
|
}
|
|
87
|
-
throw new
|
|
87
|
+
throw new config_repair_error_1.ConfigRepairError(this.formatParseFailure(configPath, lastError), [
|
|
88
|
+
new config_repair_error_1.EditFileCure(configPath, `Edit ${configPath} to restore valid JSON.`),
|
|
89
|
+
]);
|
|
88
90
|
}
|
|
89
91
|
// ONE read+parse attempt. The read is inside the try too: a file being replaced can momentarily
|
|
90
92
|
// fail to open (ENOENT between unlink and rename), which is the same transient class as a
|
package/src/config-file.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config-file.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/config-file.ts"],"names":[],"mappings":";;;AAgJA,wCAEC;AAKD,sCAEC;;AAzJD,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,8DAA0D;AAC1D,iEAA6D;AAEhD,QAAA,eAAe,GAAG,uBAAuB,CAAC;AAEvD;;;;;;;;;GASG;AACU,QAAA,qBAAqB,GAAG,CAAC,CAAC;AAEvC,uGAAuG;AAC1F,QAAA,yBAAyB,GAAG,EAAE,CAAC;AAE5C;;;GAGG;AACH,MAAa,kBAAkB;IAEd;IACA;IAFb,YACa,MAA4B,EAC5B,KAAmB;QADnB,WAAM,GAAN,MAAM,CAAsB;QAC5B,UAAK,GAAL,KAAK,CAAc;IAC7B,CAAC;CACP;AALD,gDAKC;AAED,2GAA2G;AAC3G,MAAa,aAAa;IACtB,iGAAiG;IACjG,SAAS,CAAW;IACpB,wFAAwF;IACxF,QAAQ,CAAW;IACnB,6FAA6F;IAC7F,YAAY,CAAW;IACvB,6FAA6F;IAC7F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AAED,sGAAsG;AACtG,oGAAoG;AACpG,MAAM,aAAa,GAAG,IAAI,UAAU,EAAE,CAAC;AAEvC;;GAEG;AACH,SAAgB,cAAc,CAAC,QAAgB;IAC3C,OAAO,aAAa,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;AAClD,CAAC;AAED;;GAEG;AACH,SAAgB,aAAa,CAAC,UAAkB;IAC5C,OAAO,aAAa,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC;AACnD,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { InformAiError } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\n\nexport const CONFIG_FILENAME = 'webpieces.config.json';\n\n/**\n * How many times a read+parse of webpieces.config.json is attempted before the failure is treated as\n * REAL. On a machine running several agents at once the file is routinely rewritten underneath us\n * (a dep bump, another worktree's `wp-*` command, an editor's write-then-rename), and for the few\n * milliseconds of that write the bytes on disk are a truncated/half-written JSON document. Reading\n * exactly then produced a hard block that self-healed seconds later — a false positive that also\n * blocked the tools needed to look into it. Three attempts spanning ~50ms covers a normal write with\n * a cost no human or agent can perceive, and cannot mask a file that is genuinely malformed (a\n * conflict-marked or typo'd config fails all three, identically, and still blocks).\n */\nexport const CONFIG_PARSE_ATTEMPTS = 3;\n\n/** Pause between parse attempts. Small enough to be invisible, long enough to outlast a file write. */\nexport const CONFIG_PARSE_RETRY_MILLIS = 25;\n\n/**\n * One read+parse attempt: EITHER a parsed config OR the error that attempt hit, never both.\n * Data-only (per CLAUDE.md, classes for data).\n */\nexport class ConfigParseAttempt {\n constructor(\n readonly config: RawConfigFile | null,\n readonly error: Error | null,\n ) {}\n}\n\n/** Parsed but unvalidated root declaration. Concrete policy settings live only in declared owner files. */\nexport class RawConfigFile {\n // webpieces-disable no-any-unknown -- opaque client JSON is validated at the root/owner boundary\n rulePacks?: unknown;\n // webpieces-disable no-any-unknown -- command behavior has its own structural validator\n commands?: unknown;\n // webpieces-disable no-any-unknown -- generic exclusions are validated before interpretation\n excludePaths?: unknown;\n // webpieces-disable no-any-unknown -- client match rules have their own structural validator\n 'match-rules'?: unknown;\n}\n\n/**\n * Locates + reads webpieces.config.json. `@injectable(bindingScopeValues.Singleton)` so it can be injected into the config\n * loader and appear in the rules-config DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ConfigFile {\n /** Walk up from `startDir` looking for webpieces.config.json. Returns its absolute path or null. */\n findConfigFile(startDir: string): string | null {\n let dir = startDir;\n while (true) {\n const primary = path.join(dir, CONFIG_FILENAME);\n if (fs.existsSync(primary)) return primary;\n const parent = path.dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n }\n\n /**\n * Read + JSON.parse webpieces.config.json, RETRYING a failed attempt before escalating.\n *\n * A single failed read is not evidence of a broken config: another process on this machine may be\n * mid-write, and a half-written file is unparseable for a few milliseconds and then fine. Only a\n * failure that survives every attempt is treated as real — and then it still throws, so a\n * genuinely invalid config blocks exactly as before. See {@link CONFIG_PARSE_ATTEMPTS}.\n */\n readRawConfig(configPath: string): RawConfigFile {\n let lastError: Error | null = null;\n for (let attempt = 1; attempt <= CONFIG_PARSE_ATTEMPTS; attempt++) {\n if (attempt > 1) this.sleepSync(CONFIG_PARSE_RETRY_MILLIS);\n const outcome = this.attemptReadAndParse(configPath);\n if (outcome.config !== null) return outcome.config;\n lastError = outcome.error;\n }\n throw new InformAiError(this.formatParseFailure(configPath, lastError));\n }\n\n // ONE read+parse attempt. The read is inside the try too: a file being replaced can momentarily\n // fail to open (ENOENT between unlink and rename), which is the same transient class as a\n // half-written parse failure and must be retried the same way.\n private attemptReadAndParse(configPath: string): ConfigParseAttempt {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const raw = this.readFileText(configPath);\n return new ConfigParseAttempt(JSON.parse(raw) as RawConfigFile, null);\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n return new ConfigParseAttempt(null, error);\n }\n }\n\n /** Read the file's bytes. `protected` so a test can inject a transient failure deterministically. */\n protected readFileText(configPath: string): string {\n return fs.readFileSync(configPath, 'utf8');\n }\n\n /**\n * Block this thread for `millis`. The hook path is synchronous top to bottom (a PreToolUse hook\n * answers on stdout before the tool runs), so an async delay is not available; `Atomics.wait` on a\n * never-notified word is the standard dependency-free synchronous sleep.\n */\n protected sleepSync(millis: number): void {\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, millis);\n }\n\n // The AI-facing message for a parse failure that survived every attempt. It names the retry count\n // on purpose: an agent that sees \"invalid JSON\" for a file that reads fine three seconds later has\n // no way to tell a race from a real syntax error, and the FIRST thing it needs to know is that\n // read-only inspection of the file is still available so it can go look.\n private formatParseFailure(configPath: string, error: Error | null): string {\n return (\n `webpieces.config.json could not be parsed as JSON — retried ${CONFIG_PARSE_ATTEMPTS} times ` +\n `over ~${CONFIG_PARSE_RETRY_MILLIS * (CONFIG_PARSE_ATTEMPTS - 1)}ms and it failed every time.\\n` +\n `Parse error: ${error?.message ?? 'unknown'}\\n` +\n `File: ${configPath}\\n\\n` +\n `Two causes, in the order to check them:\\n` +\n ` 1. GENUINELY INVALID — most likely. Look at the file: a trailing comma, a missing brace, ` +\n `or leftover conflict markers (\\`<<<<<<< HEAD\\`) from a merge you are in the middle of.\\n` +\n ` 2. STILL BEING WRITTEN by another process (another agent/worktree on this machine, a dep ` +\n `bump, an editor save). ${CONFIG_PARSE_ATTEMPTS} attempts already ruled out a brief write, but a ` +\n `long-running writer can outlast them — if so, simply retrying your command now will succeed.\\n\\n` +\n `👉 READING AND EDITING ${CONFIG_FILENAME} IS ALWAYS ALLOWED, including right now: \\`Read\\`, ` +\n `\\`cat\\`, \\`grep\\`, \\`sed -n\\` and the other read-only inspection commands still work while the ` +\n `config is broken. Go look at the file, fix it, then retry. (Writes to OTHER files stay ` +\n `blocked — with an unparseable config every guard is disabled, so nothing else may proceed.)`\n );\n }\n}\n\n// Temporary migration delegators — consumers migrate to injecting ConfigFile over follow-up PRs, then\n// these free functions are removed. Declarations kept identical to the originals (unchanged lines).\nconst configFileSvc = new ConfigFile();\n\n/**\n * Walk up from `startDir` looking for webpieces.config.json. Returns its absolute path or null.\n */\nexport function findConfigFile(startDir: string): string | null {\n return configFileSvc.findConfigFile(startDir);\n}\n\n/**\n * Read + JSON.parse webpieces.config.json, surfacing parse failures as a readable InformAiError.\n */\nexport function readRawConfig(configPath: string): RawConfigFile {\n return configFileSvc.readRawConfig(configPath);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"config-file.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/config-file.ts"],"names":[],"mappings":";;;AAkJA,wCAEC;AAKD,sCAEC;;AA3JD,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,iEAA6D;AAC7D,+DAAwE;AAE3D,QAAA,eAAe,GAAG,uBAAuB,CAAC;AAEvD;;;;;;;;;GASG;AACU,QAAA,qBAAqB,GAAG,CAAC,CAAC;AAEvC,uGAAuG;AAC1F,QAAA,yBAAyB,GAAG,EAAE,CAAC;AAE5C;;;GAGG;AACH,MAAa,kBAAkB;IAEd;IACA;IAFb,YACa,MAA4B,EAC5B,KAAmB;QADnB,WAAM,GAAN,MAAM,CAAsB;QAC5B,UAAK,GAAL,KAAK,CAAc;IAC7B,CAAC;CACP;AALD,gDAKC;AAED,2GAA2G;AAC3G,MAAa,aAAa;IACtB,iGAAiG;IACjG,SAAS,CAAW;IACpB,wFAAwF;IACxF,QAAQ,CAAW;IACnB,6FAA6F;IAC7F,YAAY,CAAW;IACvB,6FAA6F;IAC7F,aAAa,CAAW;CAC3B;AATD,sCASC;AAED;;;GAGG;AAEI,IAAM,UAAU,GAAhB,MAAM,UAAU;IACnB,oGAAoG;IACpG,cAAc,CAAC,QAAgB;QAC3B,IAAI,GAAG,GAAG,QAAQ,CAAC;QACnB,OAAO,IAAI,EAAE,CAAC;YACV,MAAM,OAAO,GA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,aAAa,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;AAClD,CAAC;AAED;;GAEG;AACH,SAAgB,aAAa,CAAC,UAAkB;IAC5C,OAAO,aAAa,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC;AACnD,CAAC","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { ConfigRepairError, EditFileCure } from './config-repair-error';\n\nexport const CONFIG_FILENAME = 'webpieces.config.json';\n\n/**\n * How many times a read+parse of webpieces.config.json is attempted before the failure is treated as\n * REAL. On a machine running several agents at once the file is routinely rewritten underneath us\n * (a dep bump, another worktree's `wp-*` command, an editor's write-then-rename), and for the few\n * milliseconds of that write the bytes on disk are a truncated/half-written JSON document. Reading\n * exactly then produced a hard block that self-healed seconds later — a false positive that also\n * blocked the tools needed to look into it. Three attempts spanning ~50ms covers a normal write with\n * a cost no human or agent can perceive, and cannot mask a file that is genuinely malformed (a\n * conflict-marked or typo'd config fails all three, identically, and still blocks).\n */\nexport const CONFIG_PARSE_ATTEMPTS = 3;\n\n/** Pause between parse attempts. Small enough to be invisible, long enough to outlast a file write. */\nexport const CONFIG_PARSE_RETRY_MILLIS = 25;\n\n/**\n * One read+parse attempt: EITHER a parsed config OR the error that attempt hit, never both.\n * Data-only (per CLAUDE.md, classes for data).\n */\nexport class ConfigParseAttempt {\n constructor(\n readonly config: RawConfigFile | null,\n readonly error: Error | null,\n ) {}\n}\n\n/** Parsed but unvalidated root declaration. Concrete policy settings live only in declared owner files. */\nexport class RawConfigFile {\n // webpieces-disable no-any-unknown -- opaque client JSON is validated at the root/owner boundary\n rulePacks?: unknown;\n // webpieces-disable no-any-unknown -- command behavior has its own structural validator\n commands?: unknown;\n // webpieces-disable no-any-unknown -- generic exclusions are validated before interpretation\n excludePaths?: unknown;\n // webpieces-disable no-any-unknown -- client match rules have their own structural validator\n 'match-rules'?: unknown;\n}\n\n/**\n * Locates + reads webpieces.config.json. `@injectable(bindingScopeValues.Singleton)` so it can be injected into the config\n * loader and appear in the rules-config DI design.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class ConfigFile {\n /** Walk up from `startDir` looking for webpieces.config.json. Returns its absolute path or null. */\n findConfigFile(startDir: string): string | null {\n let dir = startDir;\n while (true) {\n const primary = path.join(dir, CONFIG_FILENAME);\n if (fs.existsSync(primary)) return primary;\n const parent = path.dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n }\n\n /**\n * Read + JSON.parse webpieces.config.json, RETRYING a failed attempt before escalating.\n *\n * A single failed read is not evidence of a broken config: another process on this machine may be\n * mid-write, and a half-written file is unparseable for a few milliseconds and then fine. Only a\n * failure that survives every attempt is treated as real — and then it still throws, so a\n * genuinely invalid config blocks exactly as before. See {@link CONFIG_PARSE_ATTEMPTS}.\n */\n readRawConfig(configPath: string): RawConfigFile {\n let lastError: Error | null = null;\n for (let attempt = 1; attempt <= CONFIG_PARSE_ATTEMPTS; attempt++) {\n if (attempt > 1) this.sleepSync(CONFIG_PARSE_RETRY_MILLIS);\n const outcome = this.attemptReadAndParse(configPath);\n if (outcome.config !== null) return outcome.config;\n lastError = outcome.error;\n }\n throw new ConfigRepairError(this.formatParseFailure(configPath, lastError), [\n new EditFileCure(configPath, `Edit ${configPath} to restore valid JSON.`),\n ]);\n }\n\n // ONE read+parse attempt. The read is inside the try too: a file being replaced can momentarily\n // fail to open (ENOENT between unlink and rename), which is the same transient class as a\n // half-written parse failure and must be retried the same way.\n private attemptReadAndParse(configPath: string): ConfigParseAttempt {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const raw = this.readFileText(configPath);\n return new ConfigParseAttempt(JSON.parse(raw) as RawConfigFile, null);\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n return new ConfigParseAttempt(null, error);\n }\n }\n\n /** Read the file's bytes. `protected` so a test can inject a transient failure deterministically. */\n protected readFileText(configPath: string): string {\n return fs.readFileSync(configPath, 'utf8');\n }\n\n /**\n * Block this thread for `millis`. The hook path is synchronous top to bottom (a PreToolUse hook\n * answers on stdout before the tool runs), so an async delay is not available; `Atomics.wait` on a\n * never-notified word is the standard dependency-free synchronous sleep.\n */\n protected sleepSync(millis: number): void {\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, millis);\n }\n\n // The AI-facing message for a parse failure that survived every attempt. It names the retry count\n // on purpose: an agent that sees \"invalid JSON\" for a file that reads fine three seconds later has\n // no way to tell a race from a real syntax error, and the FIRST thing it needs to know is that\n // read-only inspection of the file is still available so it can go look.\n private formatParseFailure(configPath: string, error: Error | null): string {\n return (\n `webpieces.config.json could not be parsed as JSON — retried ${CONFIG_PARSE_ATTEMPTS} times ` +\n `over ~${CONFIG_PARSE_RETRY_MILLIS * (CONFIG_PARSE_ATTEMPTS - 1)}ms and it failed every time.\\n` +\n `Parse error: ${error?.message ?? 'unknown'}\\n` +\n `File: ${configPath}\\n\\n` +\n `Two causes, in the order to check them:\\n` +\n ` 1. GENUINELY INVALID — most likely. Look at the file: a trailing comma, a missing brace, ` +\n `or leftover conflict markers (\\`<<<<<<< HEAD\\`) from a merge you are in the middle of.\\n` +\n ` 2. STILL BEING WRITTEN by another process (another agent/worktree on this machine, a dep ` +\n `bump, an editor save). ${CONFIG_PARSE_ATTEMPTS} attempts already ruled out a brief write, but a ` +\n `long-running writer can outlast them — if so, simply retrying your command now will succeed.\\n\\n` +\n `👉 READING AND EDITING ${CONFIG_FILENAME} IS ALWAYS ALLOWED, including right now: \\`Read\\`, ` +\n `\\`cat\\`, \\`grep\\`, \\`sed -n\\` and the other read-only inspection commands still work while the ` +\n `config is broken. Go look at the file, fix it, then retry. (Writes to OTHER files stay ` +\n `blocked — with an unparseable config every guard is disabled, so nothing else may proceed.)`\n );\n }\n}\n\n// Temporary migration delegators — consumers migrate to injecting ConfigFile over follow-up PRs, then\n// these free functions are removed. Declarations kept identical to the originals (unchanged lines).\nconst configFileSvc = new ConfigFile();\n\n/**\n * Walk up from `startDir` looking for webpieces.config.json. Returns its absolute path or null.\n */\nexport function findConfigFile(startDir: string): string | null {\n return configFileSvc.findConfigFile(startDir);\n}\n\n/**\n * Read + JSON.parse webpieces.config.json, surfacing parse failures as a readable InformAiError.\n */\nexport function readRawConfig(configPath: string): RawConfigFile {\n return configFileSvc.readRawConfig(configPath);\n}\n"]}
|
package/src/config-key-rules.js
CHANGED
|
@@ -32,7 +32,7 @@ function validateTopLevelKeys(raw) {
|
|
|
32
32
|
? 'Declare a client-owned rule pack with a schema and implementation module; directory scanning is retired.'
|
|
33
33
|
: key === 'extends'
|
|
34
34
|
? 'Declare exact rulePacks and explicit owner files; inherited central config is retired.'
|
|
35
|
-
: '
|
|
35
|
+
: 'Move each entry it holds into the owner file its pack declares in rulePacks (.webpieces-config/rules/<pack>.json), then delete this key.'));
|
|
36
36
|
return [
|
|
37
37
|
...errors,
|
|
38
38
|
...unknownKeyErrors(raw, [...TOP_LEVEL_KEYS, 'pr-gate', ...retired], '[webpieces.config.json]'),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config-key-rules.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/config-key-rules.ts"],"names":[],"mappings":";;;AAwBA,oDAqBC;AAeD,oCAEC;AASD,4CAsBC;AA7FD,+DAAqD;AAErD,0GAA0G;AAC1G,qFAAqF;AACrF,sGAAsG;AACtG,yBAAyB;AAEzB;;;;GAIG;AACH,MAAM,cAAc,GAAsB,CAAC,WAAW,EAAE,UAAU,EAAE,cAAc,EAAE,aAAa,CAAC,CAAC;AAEnG;;;;;;GAMG;AACH,oGAAoG;AACpG,8GAA8G;AAC9G,6GAA6G;AAC7G,SAAgB,oBAAoB,CAAC,GAA4B;IAC7D,MAAM,OAAO,GAAG,CAAC,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC,MAAM,CAAC,CAAC,GAAW,EAAE,EAAE,CAClF,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,CAC1B,CAAC;IACF,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CACtB,CAAC,GAAW,EAAE,EAAE,CACZ,kDAAkD,GAAG,KAAK;QAC1D,CAAC,GAAG,KAAK,UAAU;YACf,CAAC,CAAC,0GAA0G;YAC5G,CAAC,CAAC,GAAG,KAAK,SAAS;gBACjB,CAAC,CAAC,wFAAwF;gBAC1F,CAAC,CAAC,
|
|
1
|
+
{"version":3,"file":"config-key-rules.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/config-key-rules.ts"],"names":[],"mappings":";;;AAwBA,oDAqBC;AAeD,oCAEC;AASD,4CAsBC;AA7FD,+DAAqD;AAErD,0GAA0G;AAC1G,qFAAqF;AACrF,sGAAsG;AACtG,yBAAyB;AAEzB;;;;GAIG;AACH,MAAM,cAAc,GAAsB,CAAC,WAAW,EAAE,UAAU,EAAE,cAAc,EAAE,aAAa,CAAC,CAAC;AAEnG;;;;;;GAMG;AACH,oGAAoG;AACpG,8GAA8G;AAC9G,6GAA6G;AAC7G,SAAgB,oBAAoB,CAAC,GAA4B;IAC7D,MAAM,OAAO,GAAG,CAAC,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC,MAAM,CAAC,CAAC,GAAW,EAAE,EAAE,CAClF,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,CAC1B,CAAC;IACF,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CACtB,CAAC,GAAW,EAAE,EAAE,CACZ,kDAAkD,GAAG,KAAK;QAC1D,CAAC,GAAG,KAAK,UAAU;YACf,CAAC,CAAC,0GAA0G;YAC5G,CAAC,CAAC,GAAG,KAAK,SAAS;gBACjB,CAAC,CAAC,wFAAwF;gBAC1F,CAAC,CAAC,0IAA0I,CAAC,CAC1J,CAAC;IACF,OAAO;QACH,GAAG,MAAM;QACT,GAAG,gBAAgB,CACf,GAAG,EACH,CAAC,GAAG,cAAc,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC,EAC1C,yBAAyB,CAC5B;KACJ,CAAC;AACN,CAAC;AAED;;;;;;;;;GASG;AACU,QAAA,kBAAkB,GAAG,KAAK,CAAC;AAExC,8GAA8G;AAC9G,SAAgB,YAAY,CAAC,GAAW;IACpC,OAAO,GAAG,CAAC,MAAM,GAAG,0BAAkB,CAAC,MAAM,IAAI,GAAG,CAAC,QAAQ,CAAC,0BAAkB,CAAC,CAAC;AACtF,CAAC;AAED;;;;GAIG;AACH,iGAAiG;AACjG,8GAA8G;AAC9G,SAAgB,gBAAgB;AAC5B,6GAA6G;AAC7G,OAAgC,EAChC,SAA4B,EAC5B,KAAa;IAEb,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QACrC,IAAI,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,IAAA,kCAAY,EAAC,GAAG,EAAE,KAAK,CAAC;YAAE,SAAS;QAClE,IAAI,YAAY,CAAC,GAAG,CAAC,EAAE,CAAC;YACpB,IAAI,OAAO,OAAO,CAAC,GAAG,CAAC,KAAK,QAAQ,EAAE,CAAC;gBACnC,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,KAAK,GAAG,kDAAkD,CAAC,CAAC;YACpF,CAAC;YACD,SAAS;QACb,CAAC;QACD,MAAM,CAAC,IAAI,CACP,GAAG,KAAK,iBAAiB,GAAG,mBAAmB,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK;YACpE,6FAA6F;YAC7F,oGAAoG,CAC3G,CAAC;IACN,CAAC;IACD,OAAO,MAAM,CAAC;AAClB,CAAC","sourcesContent":["import { isRetiredKey } from './retired-config-keys';\n\n// Key-level rules every webpieces.config.json section shares: strict unknown-key rejection and the `*Why`\n// comment convention. Its own module because both validate-config.ts (top level) and\n// commands-section-validators.ts (the commands section) need it, and either importing the other would\n// close an import cycle.\n\n/**\n * Every key webpieces.config.json defines at the TOP level. `pr-gate` is deliberately absent — it is the\n * retired top-level block, and validateCommandsSection already reports it with the move instruction, so\n * listing it here would replace that precise message with a generic \"unknown key\".\n */\nconst TOP_LEVEL_KEYS: readonly string[] = ['rulePacks', 'commands', 'excludePaths', 'match-rules'];\n\n/**\n * Reject unknown TOP-LEVEL keys. Without this, a key that was retired at the top level (or simply\n * misspelled) is silently ignored — the config looks configured and behaves as if it were not, and the dead\n * key survives every upgrade. `*Why` rationale keys are allowed, which is what lets the file document\n * itself: this repo ships a top-level `upgradePolicyWhy` stating that config is validated on startup and\n * migrated by the agent, so no backwards-compatible release is needed.\n */\n// webpieces-disable no-any-unknown -- the raw parsed config is opaque; only key names are read here\n// webpieces-disable no-function-outside-class -- module-level config validator, matches the rest of this file\n// webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\nexport function validateTopLevelKeys(raw: Record<string, unknown>): string[] {\n const retired = ['rules', 'hookGuards', 'rulesDir', 'extends'].filter((key: string) =>\n Object.hasOwn(raw, key),\n );\n const errors = retired.map(\n (key: string) =>\n `[webpieces.config.json] Retired top-level key \"${key}\". ` +\n (key === 'rulesDir'\n ? 'Declare a client-owned rule pack with a schema and implementation module; directory scanning is retired.'\n : key === 'extends'\n ? 'Declare exact rulePacks and explicit owner files; inherited central config is retired.'\n : 'Move each entry it holds into the owner file its pack declares in rulePacks (.webpieces-config/rules/<pack>.json), then delete this key.'),\n );\n return [\n ...errors,\n ...unknownKeyErrors(\n raw,\n [...TOP_LEVEL_KEYS, 'pr-gate', ...retired],\n '[webpieces.config.json]',\n ),\n ];\n}\n\n/**\n * The `*Why` convention: any key ending in \"Why\" is free-form rationale a consumer keeps beside the key it\n * explains. JSON has no comments, so this is how this repo documents non-obvious config — and it is the only\n * way the config file can carry the note that matters most to the agent reading it (see the top-level\n * \"upgradePolicyWhy\" this repo ships). Comment keys are therefore allowed wherever unknown keys are\n * otherwise rejected, and must be strings.\n *\n * ONE exception, enforced separately: `gateSaltWhy` is rejected outright, because rationale next to the gate\n * salt is a bypass how-to in the most-read file in the repo. See validateNoGateSaltRationale.\n */\nexport const COMMENT_KEY_SUFFIX = 'Why';\n\n// webpieces-disable no-function-outside-class -- module-level config validator, matches the rest of this file\nexport function isCommentKey(key: string): boolean {\n return key.length > COMMENT_KEY_SUFFIX.length && key.endsWith(COMMENT_KEY_SUFFIX);\n}\n\n/**\n * Reject keys a section does not define. Without this a retired or misspelled key is simply ignored, which is\n * how a stale shape survives an upgrade forever — the whole failure mode RETIRED_CONFIG_KEYS exists to end.\n * Retired keys are skipped here so they get their own migration message instead of a generic \"unknown key\".\n */\n// webpieces-disable no-any-unknown -- `section` is opaque consumer JSON; only key names are read\n// webpieces-disable no-function-outside-class -- module-level config validator, matches the rest of this file\nexport function unknownKeyErrors(\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n section: Record<string, unknown>,\n knownKeys: readonly string[],\n label: string,\n): string[] {\n const errors: string[] = [];\n for (const key of Object.keys(section)) {\n if (knownKeys.includes(key) || isRetiredKey(key, label)) continue;\n if (isCommentKey(key)) {\n if (typeof section[key] !== 'string') {\n errors.push(`${label} \"${key}\" is a *Why rationale note and must be a string.`);\n }\n continue;\n }\n errors.push(\n `${label} Unknown key \"${key}\". Valid keys: [${knownKeys.join(', ')}]. ` +\n `Delete it, or — if it is rationale you want to keep beside a key — rename it to \"<key>Why\" ` +\n `with a string value (JSON has no comments, so \"*Why\" siblings are how this repo documents config).`,\n );\n }\n return errors;\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** Generated from ConfigRepairProbe by pnpm guards:generate; never edit this artifact. */
|
|
2
|
-
export declare const CONFIG_REPAIR_BOOTSTRAP_SOURCE = "
|
|
2
|
+
export declare const CONFIG_REPAIR_BOOTSTRAP_SOURCE = "/**\n * Self-contained Node probe: serialized into the POSIX shim so repairs work with missing packages.\n *\n * A REPAIR FILE is one a config-repair deny can tell the agent to edit, so it is permitted while the\n * config is invalid: the root `webpieces.config.json`, `.gitignore`, everything under `.webpieces-config/`,\n * and any owner file `rulePacks` declares elsewhere. Nothing that resolves outside the repository counts.\n */\nclass ConfigRepairProbe {\n rootFor(cwd) {\n const fs = require('node:fs'), path = require('node:path');\n let directory = path.resolve(cwd);\n while (!fs.existsSync(path.join(directory, 'webpieces.config.json'))) {\n const parent = path.dirname(directory);\n if (parent === directory)\n return cwd;\n directory = parent;\n }\n return directory;\n }\n isRepairPatch(root, patch) {\n const lines = patch.trim().split('\\n');\n if (lines[0] !== '*** Begin Patch' || lines.at(-1) !== '*** End Patch')\n return false;\n let targets = 0;\n for (const line of lines.slice(1, -1)) {\n if (!line.startsWith('*** '))\n continue;\n const match = /^\\*\\*\\* (?:Add|Update) File: (.+)$/.exec(line);\n if (!match || !this.isRepairFile(root, match[1]))\n return false;\n targets += 1;\n }\n return targets > 0;\n }\n isRepairFile(root, filename) {\n const toError = this.error;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- bootstrap cannot trust package imports or malformed declarations\n try {\n const fs = require('node:fs'), path = require('node:path');\n const target = this.canonical(root, path.resolve(root, filename));\n const rootFile = this.canonical(root, path.join(root, 'webpieces.config.json'));\n if (target === rootFile || target === this.canonical(root, path.join(root, '.gitignore')))\n return true;\n const policy = path.relative(this.canonical(root, path.join(root, '.webpieces-config')), target);\n if (policy !== '' && !policy.startsWith('..') && !path.isAbsolute(policy))\n return true;\n // webpieces-disable no-any-unknown -- only validated declaration strings grant repair access\n const raw = JSON.parse(fs.readFileSync(rootFile, 'utf8'));\n if (!raw || typeof raw !== 'object' || !('rulePacks' in raw) || !Array.isArray(raw.rulePacks))\n return false;\n for (const declaration of raw.rulePacks) {\n if (declaration &&\n typeof declaration === 'object' &&\n typeof declaration.config === 'string' &&\n declaration.config.endsWith('.json') &&\n !path.isAbsolute(declaration.config) &&\n this.canonical(root, path.join(root, declaration.config)) === target)\n return true;\n }\n return false;\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n }\n catch (err) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n canonical(root, filename) {\n const fs = require('node:fs'), path = require('node:path');\n const pending = [];\n let ancestor = filename;\n while (!fs.lstatSync(ancestor, { throwIfNoEntry: false })) {\n pending.unshift(path.basename(ancestor));\n const parent = path.dirname(ancestor);\n if (parent === ancestor)\n throw new Error('Cannot resolve config repair path.');\n ancestor = parent;\n }\n const canonical = path.resolve(fs.realpathSync(ancestor), ...pending), relative = path.relative(fs.realpathSync(root), canonical);\n if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))\n throw new Error('Config repair path escapes the repository.');\n return canonical;\n }\n // webpieces-disable no-any-unknown -- the bootstrap adapter must remain self-contained when node_modules is corrupt\n error(err) {\n return err instanceof Error ? err : new Error(String(err));\n }\n}\n";
|
|
@@ -3,5 +3,5 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.CONFIG_REPAIR_BOOTSTRAP_SOURCE = void 0;
|
|
4
4
|
/** Generated from ConfigRepairProbe by pnpm guards:generate; never edit this artifact. */
|
|
5
5
|
// webpieces-disable no-unmanaged-exceptions -- serialized bootstrap catches malformed external declarations without package imports
|
|
6
|
-
exports.CONFIG_REPAIR_BOOTSTRAP_SOURCE = "
|
|
6
|
+
exports.CONFIG_REPAIR_BOOTSTRAP_SOURCE = "/**\n * Self-contained Node probe: serialized into the POSIX shim so repairs work with missing packages.\n *\n * A REPAIR FILE is one a config-repair deny can tell the agent to edit, so it is permitted while the\n * config is invalid: the root `webpieces.config.json`, `.gitignore`, everything under `.webpieces-config/`,\n * and any owner file `rulePacks` declares elsewhere. Nothing that resolves outside the repository counts.\n */\nclass ConfigRepairProbe {\n rootFor(cwd) {\n const fs = require('node:fs'), path = require('node:path');\n let directory = path.resolve(cwd);\n while (!fs.existsSync(path.join(directory, 'webpieces.config.json'))) {\n const parent = path.dirname(directory);\n if (parent === directory)\n return cwd;\n directory = parent;\n }\n return directory;\n }\n isRepairPatch(root, patch) {\n const lines = patch.trim().split('\\n');\n if (lines[0] !== '*** Begin Patch' || lines.at(-1) !== '*** End Patch')\n return false;\n let targets = 0;\n for (const line of lines.slice(1, -1)) {\n if (!line.startsWith('*** '))\n continue;\n const match = /^\\*\\*\\* (?:Add|Update) File: (.+)$/.exec(line);\n if (!match || !this.isRepairFile(root, match[1]))\n return false;\n targets += 1;\n }\n return targets > 0;\n }\n isRepairFile(root, filename) {\n const toError = this.error;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- bootstrap cannot trust package imports or malformed declarations\n try {\n const fs = require('node:fs'), path = require('node:path');\n const target = this.canonical(root, path.resolve(root, filename));\n const rootFile = this.canonical(root, path.join(root, 'webpieces.config.json'));\n if (target === rootFile || target === this.canonical(root, path.join(root, '.gitignore')))\n return true;\n const policy = path.relative(this.canonical(root, path.join(root, '.webpieces-config')), target);\n if (policy !== '' && !policy.startsWith('..') && !path.isAbsolute(policy))\n return true;\n // webpieces-disable no-any-unknown -- only validated declaration strings grant repair access\n const raw = JSON.parse(fs.readFileSync(rootFile, 'utf8'));\n if (!raw || typeof raw !== 'object' || !('rulePacks' in raw) || !Array.isArray(raw.rulePacks))\n return false;\n for (const declaration of raw.rulePacks) {\n if (declaration &&\n typeof declaration === 'object' &&\n typeof declaration.config === 'string' &&\n declaration.config.endsWith('.json') &&\n !path.isAbsolute(declaration.config) &&\n this.canonical(root, path.join(root, declaration.config)) === target)\n return true;\n }\n return false;\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n }\n catch (err) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n canonical(root, filename) {\n const fs = require('node:fs'), path = require('node:path');\n const pending = [];\n let ancestor = filename;\n while (!fs.lstatSync(ancestor, { throwIfNoEntry: false })) {\n pending.unshift(path.basename(ancestor));\n const parent = path.dirname(ancestor);\n if (parent === ancestor)\n throw new Error('Cannot resolve config repair path.');\n ancestor = parent;\n }\n const canonical = path.resolve(fs.realpathSync(ancestor), ...pending), relative = path.relative(fs.realpathSync(root), canonical);\n if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))\n throw new Error('Config repair path escapes the repository.');\n return canonical;\n }\n // webpieces-disable no-any-unknown -- the bootstrap adapter must remain self-contained when node_modules is corrupt\n error(err) {\n return err instanceof Error ? err : new Error(String(err));\n }\n}\n";
|
|
7
7
|
//# sourceMappingURL=config-repair-bootstrap-source.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config-repair-bootstrap-source.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/config-repair-bootstrap-source.ts"],"names":[],"mappings":";;;AAAA,0FAA0F;AAC1F,oIAAoI;AACvH,QAAA,8BAA8B,GAAG,
|
|
1
|
+
{"version":3,"file":"config-repair-bootstrap-source.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/config-repair-bootstrap-source.ts"],"names":[],"mappings":";;;AAAA,0FAA0F;AAC1F,oIAAoI;AACvH,QAAA,8BAA8B,GAAG,o2IAAo2I,CAAC","sourcesContent":["/** Generated from ConfigRepairProbe by pnpm guards:generate; never edit this artifact. */\n// webpieces-disable no-unmanaged-exceptions -- serialized bootstrap catches malformed external declarations without package imports\nexport const CONFIG_REPAIR_BOOTSTRAP_SOURCE = \"/**\\n * Self-contained Node probe: serialized into the POSIX shim so repairs work with missing packages.\\n *\\n * A REPAIR FILE is one a config-repair deny can tell the agent to edit, so it is permitted while the\\n * config is invalid: the root `webpieces.config.json`, `.gitignore`, everything under `.webpieces-config/`,\\n * and any owner file `rulePacks` declares elsewhere. Nothing that resolves outside the repository counts.\\n */\\nclass ConfigRepairProbe {\\n rootFor(cwd) {\\n const fs = require('node:fs'), path = require('node:path');\\n let directory = path.resolve(cwd);\\n while (!fs.existsSync(path.join(directory, 'webpieces.config.json'))) {\\n const parent = path.dirname(directory);\\n if (parent === directory)\\n return cwd;\\n directory = parent;\\n }\\n return directory;\\n }\\n isRepairPatch(root, patch) {\\n const lines = patch.trim().split('\\\\n');\\n if (lines[0] !== '*** Begin Patch' || lines.at(-1) !== '*** End Patch')\\n return false;\\n let targets = 0;\\n for (const line of lines.slice(1, -1)) {\\n if (!line.startsWith('*** '))\\n continue;\\n const match = /^\\\\*\\\\*\\\\* (?:Add|Update) File: (.+)$/.exec(line);\\n if (!match || !this.isRepairFile(root, match[1]))\\n return false;\\n targets += 1;\\n }\\n return targets > 0;\\n }\\n isRepairFile(root, filename) {\\n const toError = this.error;\\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- bootstrap cannot trust package imports or malformed declarations\\n try {\\n const fs = require('node:fs'), path = require('node:path');\\n const target = this.canonical(root, path.resolve(root, filename));\\n const rootFile = this.canonical(root, path.join(root, 'webpieces.config.json'));\\n if (target === rootFile || target === this.canonical(root, path.join(root, '.gitignore')))\\n return true;\\n const policy = path.relative(this.canonical(root, path.join(root, '.webpieces-config')), target);\\n if (policy !== '' && !policy.startsWith('..') && !path.isAbsolute(policy))\\n return true;\\n // webpieces-disable no-any-unknown -- only validated declaration strings grant repair access\\n const raw = JSON.parse(fs.readFileSync(rootFile, 'utf8'));\\n if (!raw || typeof raw !== 'object' || !('rulePacks' in raw) || !Array.isArray(raw.rulePacks))\\n return false;\\n for (const declaration of raw.rulePacks) {\\n if (declaration &&\\n typeof declaration === 'object' &&\\n typeof declaration.config === 'string' &&\\n declaration.config.endsWith('.json') &&\\n !path.isAbsolute(declaration.config) &&\\n this.canonical(root, path.join(root, declaration.config)) === target)\\n return true;\\n }\\n return false;\\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\\n }\\n catch (err) {\\n const error = toError(err);\\n void error;\\n return false;\\n }\\n }\\n canonical(root, filename) {\\n const fs = require('node:fs'), path = require('node:path');\\n const pending = [];\\n let ancestor = filename;\\n while (!fs.lstatSync(ancestor, { throwIfNoEntry: false })) {\\n pending.unshift(path.basename(ancestor));\\n const parent = path.dirname(ancestor);\\n if (parent === ancestor)\\n throw new Error('Cannot resolve config repair path.');\\n ancestor = parent;\\n }\\n const canonical = path.resolve(fs.realpathSync(ancestor), ...pending), relative = path.relative(fs.realpathSync(root), canonical);\\n if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))\\n throw new Error('Config repair path escapes the repository.');\\n return canonical;\\n }\\n // webpieces-disable no-any-unknown -- the bootstrap adapter must remain self-contained when node_modules is corrupt\\n error(err) {\\n return err instanceof Error ? err : new Error(String(err));\\n }\\n}\\n\";\n"]}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { InformAiError } from '@webpieces/tooling-common';
|
|
2
|
+
import { Option } from './fix-option';
|
|
3
|
+
/**
|
|
4
|
+
* ONE way out of a config problem: edit a named file, or run a named command.
|
|
5
|
+
*
|
|
6
|
+
* Exactly one of `editFile` / `command` is set. The hooks PERMIT every cure while the config is invalid —
|
|
7
|
+
* the file through ConfigRepairAccess, the command through the L0 allowlist — and
|
|
8
|
+
* `config-repair-cures.spec.ts` (agent-workflow-rules) asserts that against every cure a config problem
|
|
9
|
+
* can name. A cure the hook would refuse is a deadlock, which is how #1273 happened.
|
|
10
|
+
*/
|
|
11
|
+
export declare class ConfigRepairCure {
|
|
12
|
+
readonly editFile: string | null;
|
|
13
|
+
readonly command: string | null;
|
|
14
|
+
readonly text: string;
|
|
15
|
+
protected constructor(editFile: string | null, command: string | null, text: string);
|
|
16
|
+
option(preferred: boolean): Option;
|
|
17
|
+
}
|
|
18
|
+
/** Edit `file` (absolute). `text` says exactly what to paste or delete there. */
|
|
19
|
+
export declare class EditFileCure extends ConfigRepairCure {
|
|
20
|
+
constructor(file: string, text: string);
|
|
21
|
+
}
|
|
22
|
+
/** Run `command`, verbatim. `text` says why. */
|
|
23
|
+
export declare class RunCommandCure extends ConfigRepairCure {
|
|
24
|
+
constructor(command: string, text: string);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* A config / policy-file problem, carrying its cures as data (#1273).
|
|
28
|
+
*
|
|
29
|
+
* It IS an `InformAiError`, so every handler that already renders those (the hook adapters, the CLIs)
|
|
30
|
+
* renders this one as a normal deny, never as a crash. The message is the problem text followed by the
|
|
31
|
+
* cures, numbered by `formatFixOptions` — the framework owns the numbering, the throw site owns the words.
|
|
32
|
+
*/
|
|
33
|
+
export declare class ConfigRepairError extends InformAiError {
|
|
34
|
+
readonly cures: readonly ConfigRepairCure[];
|
|
35
|
+
constructor(problem: string, cures: readonly ConfigRepairCure[], options?: {
|
|
36
|
+
cause?: Error;
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* `RepositoryLayout` (tooling-common, below this package) refuses policy left in `.webpieces/` with a plain
|
|
41
|
+
* InformAiError naming `wp-migrate-dirs`. This carries that same cure as data, so the layout refusal is a
|
|
42
|
+
* ConfigRepairError like every other config problem.
|
|
43
|
+
*/
|
|
44
|
+
export declare class RepositoryLayoutRepair {
|
|
45
|
+
run(check: () => void): void;
|
|
46
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RepositoryLayoutRepair = exports.ConfigRepairError = exports.RunCommandCure = exports.EditFileCure = exports.ConfigRepairCure = void 0;
|
|
4
|
+
const tooling_common_1 = require("@webpieces/tooling-common");
|
|
5
|
+
const to_error_1 = require("@webpieces/tooling-common/to-error");
|
|
6
|
+
const fix_option_1 = require("./fix-option");
|
|
7
|
+
/**
|
|
8
|
+
* ONE way out of a config problem: edit a named file, or run a named command.
|
|
9
|
+
*
|
|
10
|
+
* Exactly one of `editFile` / `command` is set. The hooks PERMIT every cure while the config is invalid —
|
|
11
|
+
* the file through ConfigRepairAccess, the command through the L0 allowlist — and
|
|
12
|
+
* `config-repair-cures.spec.ts` (agent-workflow-rules) asserts that against every cure a config problem
|
|
13
|
+
* can name. A cure the hook would refuse is a deadlock, which is how #1273 happened.
|
|
14
|
+
*/
|
|
15
|
+
class ConfigRepairCure {
|
|
16
|
+
editFile;
|
|
17
|
+
command;
|
|
18
|
+
text;
|
|
19
|
+
constructor(editFile, command, text) {
|
|
20
|
+
this.editFile = editFile;
|
|
21
|
+
this.command = command;
|
|
22
|
+
this.text = text;
|
|
23
|
+
}
|
|
24
|
+
option(preferred) {
|
|
25
|
+
return new fix_option_1.Option(this.text, preferred);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
exports.ConfigRepairCure = ConfigRepairCure;
|
|
29
|
+
/** Edit `file` (absolute). `text` says exactly what to paste or delete there. */
|
|
30
|
+
class EditFileCure extends ConfigRepairCure {
|
|
31
|
+
constructor(file, text) {
|
|
32
|
+
super(file, null, text);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
exports.EditFileCure = EditFileCure;
|
|
36
|
+
/** Run `command`, verbatim. `text` says why. */
|
|
37
|
+
class RunCommandCure extends ConfigRepairCure {
|
|
38
|
+
constructor(command, text) {
|
|
39
|
+
super(null, command, text);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
exports.RunCommandCure = RunCommandCure;
|
|
43
|
+
/**
|
|
44
|
+
* A config / policy-file problem, carrying its cures as data (#1273).
|
|
45
|
+
*
|
|
46
|
+
* It IS an `InformAiError`, so every handler that already renders those (the hook adapters, the CLIs)
|
|
47
|
+
* renders this one as a normal deny, never as a crash. The message is the problem text followed by the
|
|
48
|
+
* cures, numbered by `formatFixOptions` — the framework owns the numbering, the throw site owns the words.
|
|
49
|
+
*/
|
|
50
|
+
class ConfigRepairError extends tooling_common_1.InformAiError {
|
|
51
|
+
cures;
|
|
52
|
+
constructor(problem, cures, options) {
|
|
53
|
+
super([
|
|
54
|
+
problem,
|
|
55
|
+
...(0, fix_option_1.formatFixOptions)(cures.map((cure, index) => cure.option(index === 0))),
|
|
56
|
+
].join('\n'), options);
|
|
57
|
+
this.name = 'ConfigRepairError';
|
|
58
|
+
this.cures = cures;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
exports.ConfigRepairError = ConfigRepairError;
|
|
62
|
+
/**
|
|
63
|
+
* `RepositoryLayout` (tooling-common, below this package) refuses policy left in `.webpieces/` with a plain
|
|
64
|
+
* InformAiError naming `wp-migrate-dirs`. This carries that same cure as data, so the layout refusal is a
|
|
65
|
+
* ConfigRepairError like every other config problem.
|
|
66
|
+
*/
|
|
67
|
+
class RepositoryLayoutRepair {
|
|
68
|
+
run(check) {
|
|
69
|
+
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- converts the layout refusal into the structured repair; everything else is rethrown
|
|
70
|
+
try {
|
|
71
|
+
check();
|
|
72
|
+
// webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
const error = (0, to_error_1.toError)(err);
|
|
76
|
+
if (!(error instanceof tooling_common_1.InformAiError))
|
|
77
|
+
throw error;
|
|
78
|
+
throw new ConfigRepairError(error.message, [new RunCommandCure(tooling_common_1.MIGRATE_DIRS_COMMAND, `${tooling_common_1.MIGRATE_DIRS_COMMAND} — moves the policy files into ${tooling_common_1.POLICY_DIR}/.`)], { cause: error });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
exports.RepositoryLayoutRepair = RepositoryLayoutRepair;
|
|
83
|
+
//# sourceMappingURL=config-repair-error.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config-repair-error.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/config-repair-error.ts"],"names":[],"mappings":";;;AAAA,8DAA4F;AAC5F,iEAA6D;AAC7D,6CAAwD;AAExD;;;;;;;GAOG;AACH,MAAa,gBAAgB;IAEZ;IACA;IACA;IAHb,YACa,QAAuB,EACvB,OAAsB,EACtB,IAAY;QAFZ,aAAQ,GAAR,QAAQ,CAAe;QACvB,YAAO,GAAP,OAAO,CAAe;QACtB,SAAI,GAAJ,IAAI,C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K,YAAY,8BAAa,CAAC;gBAAE,MAAM,KAAK,CAAC;YACnD,MAAM,IAAI,iBAAiB,CACvB,KAAK,CAAC,OAAO,EACb,CAAC,IAAI,cAAc,CAAC,qCAAoB,EAAE,GAAG,qCAAoB,kCAAkC,2BAAU,IAAI,CAAC,CAAC,EACnH,EAAE,KAAK,EAAE,KAAK,EAAE,CACnB,CAAC;QACN,CAAC;IACL,CAAC;CACJ;AAhBD,wDAgBC","sourcesContent":["import { InformAiError, MIGRATE_DIRS_COMMAND, POLICY_DIR } from '@webpieces/tooling-common';\nimport { toError } from '@webpieces/tooling-common/to-error';\nimport { Option, formatFixOptions } from './fix-option';\n\n/**\n * ONE way out of a config problem: edit a named file, or run a named command.\n *\n * Exactly one of `editFile` / `command` is set. The hooks PERMIT every cure while the config is invalid —\n * the file through ConfigRepairAccess, the command through the L0 allowlist — and\n * `config-repair-cures.spec.ts` (agent-workflow-rules) asserts that against every cure a config problem\n * can name. A cure the hook would refuse is a deadlock, which is how #1273 happened.\n */\nexport class ConfigRepairCure {\n protected constructor(\n readonly editFile: string | null,\n readonly command: string | null,\n readonly text: string,\n ) {}\n\n option(preferred: boolean): Option {\n return new Option(this.text, preferred);\n }\n}\n\n/** Edit `file` (absolute). `text` says exactly what to paste or delete there. */\nexport class EditFileCure extends ConfigRepairCure {\n constructor(file: string, text: string) {\n super(file, null, text);\n }\n}\n\n/** Run `command`, verbatim. `text` says why. */\nexport class RunCommandCure extends ConfigRepairCure {\n constructor(command: string, text: string) {\n super(null, command, text);\n }\n}\n\n/**\n * A config / policy-file problem, carrying its cures as data (#1273).\n *\n * It IS an `InformAiError`, so every handler that already renders those (the hook adapters, the CLIs)\n * renders this one as a normal deny, never as a crash. The message is the problem text followed by the\n * cures, numbered by `formatFixOptions` — the framework owns the numbering, the throw site owns the words.\n */\nexport class ConfigRepairError extends InformAiError {\n readonly cures: readonly ConfigRepairCure[];\n\n constructor(problem: string, cures: readonly ConfigRepairCure[], options?: { cause?: Error }) {\n super(\n [\n problem,\n ...formatFixOptions(cures.map((cure: ConfigRepairCure, index: number) => cure.option(index === 0))),\n ].join('\\n'),\n options,\n );\n this.name = 'ConfigRepairError';\n this.cures = cures;\n }\n}\n\n/**\n * `RepositoryLayout` (tooling-common, below this package) refuses policy left in `.webpieces/` with a plain\n * InformAiError naming `wp-migrate-dirs`. This carries that same cure as data, so the layout refusal is a\n * ConfigRepairError like every other config problem.\n */\nexport class RepositoryLayoutRepair {\n run(check: () => void): void {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- converts the layout refusal into the structured repair; everything else is rethrown\n try {\n check();\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n if (!(error instanceof InformAiError)) throw error;\n throw new ConfigRepairError(\n error.message,\n [new RunCommandCure(MIGRATE_DIRS_COMMAND, `${MIGRATE_DIRS_COMMAND} — moves the policy files into ${POLICY_DIR}/.`)],\n { cause: error },\n );\n }\n }\n}\n"]}
|
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* Self-contained Node probe: serialized into the POSIX shim so repairs work with missing packages.
|
|
3
|
+
*
|
|
4
|
+
* A REPAIR FILE is one a config-repair deny can tell the agent to edit, so it is permitted while the
|
|
5
|
+
* config is invalid: the root `webpieces.config.json`, `.gitignore`, everything under `.webpieces-config/`,
|
|
6
|
+
* and any owner file `rulePacks` declares elsewhere. Nothing that resolves outside the repository counts.
|
|
7
|
+
*/
|
|
2
8
|
export declare class ConfigRepairProbe {
|
|
3
9
|
rootFor(cwd: string): string;
|
|
4
10
|
isRepairPatch(root: string, patch: string): boolean;
|
|
@@ -2,7 +2,13 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.ConfigRepairBootstrap = exports.ConfigRepairProbe = void 0;
|
|
4
4
|
const config_repair_bootstrap_source_1 = require("./config-repair-bootstrap-source");
|
|
5
|
-
/**
|
|
5
|
+
/**
|
|
6
|
+
* Self-contained Node probe: serialized into the POSIX shim so repairs work with missing packages.
|
|
7
|
+
*
|
|
8
|
+
* A REPAIR FILE is one a config-repair deny can tell the agent to edit, so it is permitted while the
|
|
9
|
+
* config is invalid: the root `webpieces.config.json`, `.gitignore`, everything under `.webpieces-config/`,
|
|
10
|
+
* and any owner file `rulePacks` declares elsewhere. Nothing that resolves outside the repository counts.
|
|
11
|
+
*/
|
|
6
12
|
class ConfigRepairProbe {
|
|
7
13
|
rootFor(cwd) {
|
|
8
14
|
const fs = require('node:fs'), path = require('node:path');
|
|
@@ -39,39 +45,23 @@ class ConfigRepairProbe {
|
|
|
39
45
|
const rootFile = this.canonical(root, path.join(root, 'webpieces.config.json'));
|
|
40
46
|
if (target === rootFile || target === this.canonical(root, path.join(root, '.gitignore')))
|
|
41
47
|
return true;
|
|
48
|
+
const policy = path.relative(this.canonical(root, path.join(root, '.webpieces-config')), target);
|
|
49
|
+
if (policy !== '' && !policy.startsWith('..') && !path.isAbsolute(policy))
|
|
50
|
+
return true;
|
|
42
51
|
// webpieces-disable no-any-unknown -- only validated declaration strings grant repair access
|
|
43
52
|
const raw = JSON.parse(fs.readFileSync(rootFile, 'utf8'));
|
|
44
|
-
if (!raw ||
|
|
45
|
-
typeof raw !== 'object' ||
|
|
46
|
-
!('rulePacks' in raw) ||
|
|
47
|
-
!Array.isArray(raw.rulePacks) ||
|
|
48
|
-
!raw.rulePacks.length)
|
|
53
|
+
if (!raw || typeof raw !== 'object' || !('rulePacks' in raw) || !Array.isArray(raw.rulePacks))
|
|
49
54
|
return false;
|
|
50
|
-
const files = new Set(), packages = new Set();
|
|
51
|
-
const lock = this.canonical(root, path.join(root, '.webpieces-config/rules.lock.json'));
|
|
52
55
|
for (const declaration of raw.rulePacks) {
|
|
53
|
-
if (
|
|
54
|
-
typeof declaration
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
!declaration.
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
path.isAbsolute(declaration.config) ||
|
|
61
|
-
Object.keys(declaration).some((key) => !['package', 'config'].includes(key)))
|
|
62
|
-
return false;
|
|
63
|
-
const file = this.canonical(root, path.join(root, declaration.config));
|
|
64
|
-
if (file === rootFile ||
|
|
65
|
-
file === lock ||
|
|
66
|
-
files.has(file) ||
|
|
67
|
-
packages.has(declaration.package))
|
|
68
|
-
return false;
|
|
69
|
-
files.add(file);
|
|
70
|
-
packages.add(declaration.package);
|
|
56
|
+
if (declaration &&
|
|
57
|
+
typeof declaration === 'object' &&
|
|
58
|
+
typeof declaration.config === 'string' &&
|
|
59
|
+
declaration.config.endsWith('.json') &&
|
|
60
|
+
!path.isAbsolute(declaration.config) &&
|
|
61
|
+
this.canonical(root, path.join(root, declaration.config)) === target)
|
|
62
|
+
return true;
|
|
71
63
|
}
|
|
72
|
-
|
|
73
|
-
files.add(this.canonical(root, path.join(root, '.webpieces-config/rules-catalog.md')));
|
|
74
|
-
return files.has(target);
|
|
64
|
+
return false;
|
|
75
65
|
// webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution
|
|
76
66
|
}
|
|
77
67
|
catch (err) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config-repair-probe.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/config-repair-probe.ts"],"names":[],"mappings":";;;AAAA,qFAAkF;AAElF,uGAAuG;AACvG,MAAa,iBAAiB;IAC1B,OAAO,CAAC,GAAW;QACf,MAAM,EAAE,GAAG,OAAO,CAAC,SAAS,CAA6B,EACrD,IAAI,GAAG,OAAO,CAAC,WAAW,CAA+B,CAAC;QAC9D,IAAI,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAClC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,uBAAuB,CAAC,CAAC,EAAE,CAAC;YACnE,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,C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;AARD,sDAQC","sourcesContent":["import { CONFIG_REPAIR_BOOTSTRAP_SOURCE } from './config-repair-bootstrap-source';\n\n/** Self-contained Node probe: serialized into the POSIX shim so repairs work with missing packages. */\nexport class ConfigRepairProbe {\n rootFor(cwd: string): string {\n const fs = require('node:fs') as typeof import('node:fs'),\n path = require('node:path') as typeof import('node:path');\n let directory = path.resolve(cwd);\n while (!fs.existsSync(path.join(directory, 'webpieces.config.json'))) {\n const parent = path.dirname(directory);\n if (parent === directory) return cwd;\n directory = parent;\n }\n return directory;\n }\n\n isRepairPatch(root: string, patch: string): boolean {\n const lines = patch.trim().split('\\n');\n if (lines[0] !== '*** Begin Patch' || lines.at(-1) !== '*** End Patch') return false;\n let targets = 0;\n for (const line of lines.slice(1, -1)) {\n if (!line.startsWith('*** ')) continue;\n const match = /^\\*\\*\\* (?:Add|Update) File: (.+)$/.exec(line);\n if (!match || !this.isRepairFile(root, match[1])) return false;\n targets += 1;\n }\n return targets > 0;\n }\n\n isRepairFile(root: string, filename: string): boolean {\n const toError = this.error;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- bootstrap cannot trust package imports or malformed declarations\n try {\n const fs = require('node:fs') as typeof import('node:fs'),\n path = require('node:path') as typeof import('node:path');\n const target = this.canonical(root, path.resolve(root, filename));\n const rootFile = this.canonical(root, path.join(root, 'webpieces.config.json'));\n if (target === rootFile || target === this.canonical(root, path.join(root, '.gitignore'))) return true;\n // webpieces-disable no-any-unknown -- only validated declaration strings grant repair access\n const raw: unknown = JSON.parse(fs.readFileSync(rootFile, 'utf8'));\n if (\n !raw ||\n typeof raw !== 'object' ||\n !('rulePacks' in raw) ||\n !Array.isArray(raw.rulePacks) ||\n !raw.rulePacks.length\n )\n return false;\n const files = new Set<string>(),\n packages = new Set<string>();\n const lock = this.canonical(root, path.join(root, '.webpieces-config/rules.lock.json'));\n for (const declaration of raw.rulePacks) {\n if (\n !declaration ||\n typeof declaration !== 'object' ||\n Array.isArray(declaration) ||\n typeof declaration.package !== 'string' ||\n !declaration.package ||\n typeof declaration.config !== 'string' ||\n !declaration.config.endsWith('.json') ||\n path.isAbsolute(declaration.config) ||\n Object.keys(declaration).some(\n (key: string) => !['package', 'config'].includes(key),\n )\n )\n return false;\n const file = this.canonical(root, path.join(root, declaration.config));\n if (\n file === rootFile ||\n file === lock ||\n files.has(file) ||\n packages.has(declaration.package)\n )\n return false;\n files.add(file);\n packages.add(declaration.package);\n }\n files.add(lock);\n files.add(\n this.canonical(root, path.join(root, '.webpieces-config/rules-catalog.md')),\n );\n return files.has(target);\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n private canonical(root: string, filename: string): string {\n const fs = require('node:fs') as typeof import('node:fs'),\n path = require('node:path') as typeof import('node:path');\n const pending: string[] = [];\n let ancestor = filename;\n while (!fs.lstatSync(ancestor, { throwIfNoEntry: false })) {\n pending.unshift(path.basename(ancestor));\n const parent = path.dirname(ancestor);\n if (parent === ancestor) throw new Error('Cannot resolve config repair path.');\n ancestor = parent;\n }\n const canonical = path.resolve(fs.realpathSync(ancestor), ...pending),\n relative = path.relative(fs.realpathSync(root), canonical);\n if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))\n throw new Error('Config repair path escapes the repository.');\n return canonical;\n }\n\n // webpieces-disable no-any-unknown -- the bootstrap adapter must remain self-contained when node_modules is corrupt\n private error(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n }\n}\n\n/** Emits the same compiled probe class; the shell has no separate declaration/path algorithm. */\nexport class ConfigRepairBootstrap {\n script(): string {\n return `${CONFIG_REPAIR_BOOTSTRAP_SOURCE} if (!new ConfigRepairProbe().isRepairFile(process.argv[1], process.argv[2])) process.exitCode = 1;`;\n }\n\n callScript(): string {\n return `${CONFIG_REPAIR_BOOTSTRAP_SOURCE} const probe = new ConfigRepairProbe(); const root = probe.rootFor(process.argv[1]); const payload = JSON.parse(require('node:fs').readFileSync(0, 'utf8')); const input = payload.tool_input; const tool = payload.tool_name; const allowed = ['Write','Edit','MultiEdit'].includes(tool) && input && typeof input.file_path === 'string' ? probe.isRepairFile(root, input.file_path) : tool === 'apply_patch' && input && typeof input.command === 'string' && probe.isRepairPatch(root, input.command); if (!allowed) process.exitCode = 1;`;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"config-repair-probe.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/config-repair-probe.ts"],"names":[],"mappings":";;;AAAA,qFAAkF;AAElF;;;;;;GAMG;AACH,MAAa,iBAAiB;IAC1B,OAAO,CAAC,GAAW;QACf,MAAM,EAAE,GAAG,OAAO,CAAC,SAAS,CAA6B,EACrD,IAAI,GAAG,OAAO,CAAC,WAAW,CAA+B,CAAC;QAC9D,IAAI,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAClC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,uBAAuB,CAAC,CAAC,EAAE,CAAC;YACnE,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;YACvC,IAAI,MAAM,KAAK,SAAS;gBAAE,OAAO,GAAG,CAAC;YACrC,SAAS,GAAG,MAAM,CAAC;QACvB,CAAC;QACD,OAAO,SAAS,CAAC;IACrB,CAAC;IAED,aAAa,CAAC,IAAY,EAAE,KAAa;QACrC,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACvC,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,iBAAiB,IAAI,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,eAAe;YAAE,OAAO,KAAK,CAAC;QACrF,IAAI,OAAO,GAAG,CAAC,CAAC;QAChB,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CA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cesContent":["import { CONFIG_REPAIR_BOOTSTRAP_SOURCE } from './config-repair-bootstrap-source';\n\n/**\n * Self-contained Node probe: serialized into the POSIX shim so repairs work with missing packages.\n *\n * A REPAIR FILE is one a config-repair deny can tell the agent to edit, so it is permitted while the\n * config is invalid: the root `webpieces.config.json`, `.gitignore`, everything under `.webpieces-config/`,\n * and any owner file `rulePacks` declares elsewhere. Nothing that resolves outside the repository counts.\n */\nexport class ConfigRepairProbe {\n rootFor(cwd: string): string {\n const fs = require('node:fs') as typeof import('node:fs'),\n path = require('node:path') as typeof import('node:path');\n let directory = path.resolve(cwd);\n while (!fs.existsSync(path.join(directory, 'webpieces.config.json'))) {\n const parent = path.dirname(directory);\n if (parent === directory) return cwd;\n directory = parent;\n }\n return directory;\n }\n\n isRepairPatch(root: string, patch: string): boolean {\n const lines = patch.trim().split('\\n');\n if (lines[0] !== '*** Begin Patch' || lines.at(-1) !== '*** End Patch') return false;\n let targets = 0;\n for (const line of lines.slice(1, -1)) {\n if (!line.startsWith('*** ')) continue;\n const match = /^\\*\\*\\* (?:Add|Update) File: (.+)$/.exec(line);\n if (!match || !this.isRepairFile(root, match[1])) return false;\n targets += 1;\n }\n return targets > 0;\n }\n\n isRepairFile(root: string, filename: string): boolean {\n const toError = this.error;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- bootstrap cannot trust package imports or malformed declarations\n try {\n const fs = require('node:fs') as typeof import('node:fs'),\n path = require('node:path') as typeof import('node:path');\n const target = this.canonical(root, path.resolve(root, filename));\n const rootFile = this.canonical(root, path.join(root, 'webpieces.config.json'));\n if (target === rootFile || target === this.canonical(root, path.join(root, '.gitignore'))) return true;\n const policy = path.relative(this.canonical(root, path.join(root, '.webpieces-config')), target);\n if (policy !== '' && !policy.startsWith('..') && !path.isAbsolute(policy)) return true;\n // webpieces-disable no-any-unknown -- only validated declaration strings grant repair access\n const raw: unknown = JSON.parse(fs.readFileSync(rootFile, 'utf8'));\n if (!raw || typeof raw !== 'object' || !('rulePacks' in raw) || !Array.isArray(raw.rulePacks))\n return false;\n for (const declaration of raw.rulePacks) {\n if (\n declaration &&\n typeof declaration === 'object' &&\n typeof declaration.config === 'string' &&\n declaration.config.endsWith('.json') &&\n !path.isAbsolute(declaration.config) &&\n this.canonical(root, path.join(root, declaration.config)) === target\n )\n return true;\n }\n return false;\n // webpieces-disable no-any-unknown -- external JSON or runtime exports are validated before policy execution\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return false;\n }\n }\n\n private canonical(root: string, filename: string): string {\n const fs = require('node:fs') as typeof import('node:fs'),\n path = require('node:path') as typeof import('node:path');\n const pending: string[] = [];\n let ancestor = filename;\n while (!fs.lstatSync(ancestor, { throwIfNoEntry: false })) {\n pending.unshift(path.basename(ancestor));\n const parent = path.dirname(ancestor);\n if (parent === ancestor) throw new Error('Cannot resolve config repair path.');\n ancestor = parent;\n }\n const canonical = path.resolve(fs.realpathSync(ancestor), ...pending),\n relative = path.relative(fs.realpathSync(root), canonical);\n if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))\n throw new Error('Config repair path escapes the repository.');\n return canonical;\n }\n\n // webpieces-disable no-any-unknown -- the bootstrap adapter must remain self-contained when node_modules is corrupt\n private error(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n }\n}\n\n/** Emits the same compiled probe class; the shell has no separate declaration/path algorithm. */\nexport class ConfigRepairBootstrap {\n script(): string {\n return `${CONFIG_REPAIR_BOOTSTRAP_SOURCE} if (!new ConfigRepairProbe().isRepairFile(process.argv[1], process.argv[2])) process.exitCode = 1;`;\n }\n\n callScript(): string {\n return `${CONFIG_REPAIR_BOOTSTRAP_SOURCE} const probe = new ConfigRepairProbe(); const root = probe.rootFor(process.argv[1]); const payload = JSON.parse(require('node:fs').readFileSync(0, 'utf8')); const input = payload.tool_input; const tool = payload.tool_name; const allowed = ['Write','Edit','MultiEdit'].includes(tool) && input && typeof input.file_path === 'string' ? probe.isRepairFile(root, input.file_path) : tool === 'apply_patch' && input && typeof input.command === 'string' && probe.isRepairPatch(root, input.command); if (!allowed) process.exitCode = 1;`;\n }\n}\n"]}
|
package/src/index.d.ts
CHANGED
|
@@ -63,9 +63,9 @@ export * from './hook-config-diagnostics';
|
|
|
63
63
|
export { RulePackRegistry, NodeRulePackModuleLoader, RulePackDiscovery, RulePackModuleLoader, } from './rule-pack-registry';
|
|
64
64
|
export { prepareLegacyUpgrade, LegacyConfigDocument, LegacyUpgradeResult, } from './legacy-config-upgrade';
|
|
65
65
|
export { PackPolicyDeclaration, SelectedPolicyPack, PackPolicyFilesResult, PackPolicyFiles, } from './pack-policy-files';
|
|
66
|
-
export { RulePackSync
|
|
66
|
+
export { RulePackSync } from './rule-pack-sync';
|
|
67
67
|
export { ConfigRepairAccess } from './config-repair-access';
|
|
68
68
|
export { ConfigRepairBootstrap } from './config-repair-probe';
|
|
69
|
-
export {
|
|
69
|
+
export { ConfigRepairCure, ConfigRepairError, EditFileCure, RunCommandCure, RepositoryLayoutRepair, } from './config-repair-error';
|
|
70
70
|
export { RuleRuntimeModules, RuleRuntimeModuleLoader, NodeRuleRuntimeModuleLoader, RuntimeContributionGroup, } from './rule-runtime-modules';
|
|
71
71
|
export { FirstPathMatch, FirstPathMatchResult, PathMatchCandidate } from './first-path-match';
|
package/src/index.js
CHANGED
|
@@ -5,7 +5,7 @@ exports.HOME_KEY_MAX_CONCURRENT_BUILDS = exports.HOME_KEY_WHOLE_REPO_BUILD_GUARD
|
|
|
5
5
|
exports.hasChangesInRange = exports.findNewMethodSignaturesInDiff = exports.getChangedLineNumbers = exports.getFileDiff = exports.getChangedFiles = exports.resolveBase = exports.detectBase = exports.SkipRuleResult = exports.HOTFIX_AUDIT_BANNER = exports.HOTFIX_BUILD_COMMAND = exports.shouldSkipRule = exports.sectionForRule = exports.isHookGuard = exports.schemaFieldNames = exports.DEFAULT_MATCH_RULES = exports.renderMatchRuleMessage = exports.compileMatchRulePatterns = exports.isMatchRuleAllowedPath = exports.findMatchRuleViolations = exports.MatchRuleViolation = exports.MatchRuleConfig = exports.OrphanSweepReport = exports.OrphanDirSweeper = exports.TRASH_RETENTION_DAYS = exports.TRASH_MANIFEST_FILE = exports.TRASH_STATE_DIR = exports.OrphanSweepManifest = exports.OrphanSweepResult = exports.FailedOrphan = exports.ArchivedOrphan = exports.OrphanDirArchiver = exports.OrphanCandidate = exports.OrphanDirScanner = exports.MAX_ROW_BYTES = exports.BUILDS_LOG_GENERATIONS = exports.MAX_BUILDS_LOG_BYTES = exports.BUILD_DONE_FAIL = exports.BUILD_DONE_SUCCESS = exports.BUILD_START = exports.BUILDS_LOCK_FILE = exports.BUILDS_LOG_FILE = exports.RunningBuild = exports.BuildTermination = exports.BuildTicket = exports.BuildsLog = exports.DOCUMENTATION_KEYS = exports.HOME_KEY_AI_DOC = exports.HOME_KEY_DOC = exports.DEFAULT_MAX_CONCURRENT_BUILDS = exports.HOME_KEY_TURN_OFF_ALL_REVIEWERS = void 0;
|
|
6
6
|
exports.ReviewerBriefing = exports.ReviewerInstructionsService = exports.ChecklistInstructionsService = exports.ChecklistValidator = exports.formatFileList = exports.normalizeChecklistDoc = exports.toChecklist = exports.DEFAULT_REVIEWER_AGENT_NAME = exports.REVIEWER_AGENTS_PLACEHOLDER = exports.ReviewerAgentPolicy = exports.ChecklistDefinition = exports.MERGE_MODES = exports.MERGE_MODE_NONE = exports.MERGE_MODE_AUTO = exports.buildDevDeployConfig = exports.buildLandPrConfig = exports.buildPrGateConfig = exports.defaultDevDeployConfig = exports.defaultLandPrConfig = exports.defaultPrGateConfig = exports.defaultGates = exports.ReviewContextEntry = exports.DEFAULT_DEV_BRANCH = exports.DEFAULT_DEV_BRANCH_NAMESPACE = exports.DevDeployConfig = exports.LandPrConfig = exports.DEFAULT_BUILD_COMMAND = exports.PrGateConfig = exports.GateDefinition = exports.WP_FINISH_PUSH_DEV = exports.WP_PUSH_DEV = exports.WP_FINISH_UPSERT_PR = exports.WP_START_UPSERT_PR = exports.WP_FINISH_UPDATE = exports.WP_START_UPDATE = exports.SyncFlowGuidance = exports.WebpiecesRulesConfig = exports.UPGRADE_SHIM_COMMAND = exports.PRUNE_UNKNOWN_COMMAND = exports.PUSH_DEV_STATE_FILE = exports.MERGE_EXPLANATION_FILE = exports.MERGE_IN_PROGRESS_FILE = exports.MERGE_INFO_DIR = exports.hasDisable = exports.WEBPIECES_DISABLE = exports.AbstractRule = exports.ChangedFilesOptions = exports.DiffRange = exports.DiffScope = exports.isNewOrModified = void 0;
|
|
7
7
|
exports.summaryJsonPath = exports.prDirFor = exports.ReviewJsonService = exports.ChecklistReviewContext = exports.RequiredChecklist = exports.VERDICT_STATUSES = exports.VERDICT_RED = exports.VERDICT_ORANGE = exports.VERDICT_YELLOW = exports.VERDICT_GREEN = exports.CK_BAD_FORMAT = exports.CK_MISSING = exports.CK_FAIL = exports.CK_ORANGE = exports.CK_ORANGE_FIXED = exports.CK_OVERRIDDEN = exports.CK_WARN = exports.CK_PASS = exports.checklistOverrideService = exports.ChecklistOverrideService = exports.ChecklistOverride = exports.ChecklistVerdict = exports.ChecklistResult = exports.PrContext = exports.PrSummary = exports.DEFAULT_RETENTION_DAYS = exports.ProvenanceWriteRequest = exports.OfferedContext = exports.ReviewerPaths = exports.ReviewerTranscript = exports.ReviewProvenance = exports.ReviewProvenanceService = exports.PROVENANCE_SKIPPED = exports.PROVENANCE_MISSING = exports.PROVENANCE_OK = exports.ProvenanceResult = exports.TranscriptScan = exports.ExpectedReviewer = exports.ReviewerContext = exports.ReviewerEvidence = exports.SubagentProvenanceService = exports.verifyGateToken = exports.extractGateToken = exports.gateTokenMarker = exports.computeGateToken = exports.GateTokenService = exports.ALL_DIFF_ONE_READ_LINES = exports.READ_TRUNCATION_LINES = exports.ContextEntry = exports.BriefedFile = void 0;
|
|
8
|
-
exports.PathMatchCandidate = exports.FirstPathMatchResult = exports.FirstPathMatch = exports.RuntimeContributionGroup = exports.NodeRuleRuntimeModuleLoader = exports.RuleRuntimeModuleLoader = exports.RuleRuntimeModules = exports.
|
|
8
|
+
exports.PathMatchCandidate = exports.FirstPathMatchResult = exports.FirstPathMatch = exports.RuntimeContributionGroup = exports.NodeRuleRuntimeModuleLoader = exports.RuleRuntimeModuleLoader = exports.RuleRuntimeModules = exports.RepositoryLayoutRepair = exports.RunCommandCure = exports.EditFileCure = exports.ConfigRepairError = exports.ConfigRepairCure = exports.ConfigRepairBootstrap = exports.ConfigRepairAccess = exports.RulePackSync = exports.PackPolicyFiles = exports.PackPolicyFilesResult = exports.SelectedPolicyPack = exports.PackPolicyDeclaration = exports.LegacyUpgradeResult = exports.LegacyConfigDocument = exports.prepareLegacyUpgrade = exports.RulePackModuleLoader = exports.RulePackDiscovery = exports.NodeRulePackModuleLoader = exports.RulePackRegistry = exports.TMP_SCRATCH_PREFIX = exports.TMP_SCRATCH_RETENTION_DAYS = exports.TmpScratchSweeper = exports.SCRATCH_DIR_NAME = exports.RepoScratchDirs = exports.staleBinSweeper = exports.StaleBinSweeper = exports.StaleBinRemoval = exports.DEFAULT_MERGE_COMPLETE_COMMAND = exports.DEFAULT_UPSERT_PR_COMMAND = exports.buildCommandsConfig = exports.CommandsConfig = exports.summaryJsonSchemaHint = void 0;
|
|
9
9
|
const tslib_1 = require("tslib");
|
|
10
10
|
var types_1 = require("./types");
|
|
11
11
|
Object.defineProperty(exports, "ResolvedConfig", { enumerable: true, get: function () { return types_1.ResolvedConfig; } });
|
|
@@ -393,16 +393,16 @@ Object.defineProperty(exports, "PackPolicyFilesResult", { enumerable: true, get:
|
|
|
393
393
|
Object.defineProperty(exports, "PackPolicyFiles", { enumerable: true, get: function () { return pack_policy_files_1.PackPolicyFiles; } });
|
|
394
394
|
var rule_pack_sync_1 = require("./rule-pack-sync");
|
|
395
395
|
Object.defineProperty(exports, "RulePackSync", { enumerable: true, get: function () { return rule_pack_sync_1.RulePackSync; } });
|
|
396
|
-
Object.defineProperty(exports, "RulePackSyncOptions", { enumerable: true, get: function () { return rule_pack_sync_1.RulePackSyncOptions; } });
|
|
397
396
|
var config_repair_access_1 = require("./config-repair-access");
|
|
398
397
|
Object.defineProperty(exports, "ConfigRepairAccess", { enumerable: true, get: function () { return config_repair_access_1.ConfigRepairAccess; } });
|
|
399
398
|
var config_repair_probe_1 = require("./config-repair-probe");
|
|
400
399
|
Object.defineProperty(exports, "ConfigRepairBootstrap", { enumerable: true, get: function () { return config_repair_probe_1.ConfigRepairBootstrap; } });
|
|
401
|
-
var
|
|
402
|
-
Object.defineProperty(exports, "
|
|
403
|
-
Object.defineProperty(exports, "
|
|
404
|
-
Object.defineProperty(exports, "
|
|
405
|
-
Object.defineProperty(exports, "
|
|
400
|
+
var config_repair_error_1 = require("./config-repair-error");
|
|
401
|
+
Object.defineProperty(exports, "ConfigRepairCure", { enumerable: true, get: function () { return config_repair_error_1.ConfigRepairCure; } });
|
|
402
|
+
Object.defineProperty(exports, "ConfigRepairError", { enumerable: true, get: function () { return config_repair_error_1.ConfigRepairError; } });
|
|
403
|
+
Object.defineProperty(exports, "EditFileCure", { enumerable: true, get: function () { return config_repair_error_1.EditFileCure; } });
|
|
404
|
+
Object.defineProperty(exports, "RunCommandCure", { enumerable: true, get: function () { return config_repair_error_1.RunCommandCure; } });
|
|
405
|
+
Object.defineProperty(exports, "RepositoryLayoutRepair", { enumerable: true, get: function () { return config_repair_error_1.RepositoryLayoutRepair; } });
|
|
406
406
|
var rule_runtime_modules_1 = require("./rule-runtime-modules");
|
|
407
407
|
Object.defineProperty(exports, "RuleRuntimeModules", { enumerable: true, get: function () { return rule_runtime_modules_1.RuleRuntimeModules; } });
|
|
408
408
|
Object.defineProperty(exports, "RuleRuntimeModuleLoader", { enumerable: true, get: function () { return rule_runtime_modules_1.RuleRuntimeModuleLoader; } });
|