Skip to content

armgit / ECC

Public Imported from GitHub
0

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

Merge branch 'affaan-m:main' into main

Geronimo5f7ba84b3888
diff --cc package.json
index 70e37d609,57357af0e..4fd2ae347
--- a/package.json
+++ b/package.json
@@@ -491,13 -498,8 +498,13 @@@
"orchestrate:status": "node scripts/orchestration-status.js",
"orchestrate:worker": "bash scripts/orchestrate-codex-worker.sh",
"orchestrate:tmux": "node scripts/orchestrate-worktrees.js",
- "test:validators": "node scripts/ci/check-unicode-safety.js && node scripts/ci/validate-agents.js && node scripts/ci/validate-commands.js && node scripts/ci/validate-rules.js && node scripts/ci/validate-skills.js && node scripts/ci/validate-hooks.js && node scripts/ci/check-hooks-schema-keys.js && node scripts/ci/validate-install-manifests.js && node scripts/ci/validate-no-personal-paths.js && npm run catalog:check && npm run command-registry:check",
- "test": "node scripts/ci/check-unicode-safety.js && node scripts/ci/validate-agents.js && node scripts/ci/validate-commands.js && node scripts/ci/validate-rules.js && node scripts/ci/validate-skills.js && node scripts/ci/validate-hooks.js && node scripts/ci/check-hooks-schema-keys.js && node scripts/ci/validate-install-manifests.js && node scripts/ci/validate-context-profiles.js && node scripts/ci/validate-no-personal-paths.js && npm run catalog:check && npm run command-registry:check && node tests/run-all.js",
- "coverage": "c8 --all --include=\"scripts/**/*.js\" --include=\"scripts/**/*.mjs\" --check-coverage --lines 80 --functions 80 --branches 79 --statements 80 --reporter=text --reporter=lcov node tests/run-all.js",
++ "test:validators": "node scripts/ci/check-unicode-safety.js && node scripts/ci/validate-agents.js && node scripts/ci/validate-commands.js && node scripts/ci/validate-rules.js && node scripts/ci/validate-skills.js && node scripts/ci/validate-hooks.js && node scripts/ci/check-hooks-schema-keys.js && node scripts/ci/validate-install-manifests.js && node scripts/ci/validate-context-profiles.js && node scripts/ci/validate-no-personal-paths.js && npm run catalog:check && npm run command-registry:check",
+ "test:js": "node tests/run-all.js",
+ "test:python": "python3 -m pytest tests/ -q",
+ "test": "npm run test:validators && npm run test:js",
+ "coverage:js": "c8 --all --include=\"scripts/**/*.js\" --include=\"scripts/**/*.mjs\" --check-coverage --lines 80 --functions 80 --branches 79 --statements 80 --reporter=text --reporter=lcov node tests/run-all.js",
+ "coverage:python": "python3 -m pytest tests/ -q --cov=src --cov-report=term --cov-fail-under=80",
+ "coverage": "npm run coverage:js",
"build:opencode": "node scripts/build-opencode.js",
"prepack": "npm run build:opencode",
"dashboard": "python3 ./ecc_dashboard.py",
diff --cc scripts/lib/install-lifecycle.js
index 3f6c7f71a,98abf8e20..57b9ce2e9
--- a/scripts/lib/install-lifecycle.js
+++ b/scripts/lib/install-lifecycle.js
@@@ -37,31 -45,7 +44,32 @@@ const { adaptAntigravityAgent } = requi
const { buildInstallIndex, rewriteRelativeLinks } = require('./install/link-rewrite');
const { getInstallTargetAdapter, listInstallTargetAdapters } = require('./install-targets/registry');
const { resolveInvocationEnvironment } = require('./invocation-environment');
-const { mergeHooksMetadata, metadataPathFor } = require('./hooks-config');
+const {
+ assertClaudeSettingsDestination,
+ cleanupEmptyParentDirs,
+ copyContainedFile,
+ getContainedExistingPath,
+ getManagedDestination,
+ prepareContainedWriteDestination,
+ readFileNoFollow,
+ readFileWithMetadataNoFollow,
+ readHooksConfigNoFollow,
+ readJsonNoFollow,
+ removeContainedPath,
+ writeContainedFile,
++ writeFileNoFollow,
+} = require('./install/contained-fs');
+const {
+ JSON_REMOVE_SENTINEL,
+ deepMergeJson,
+ deepRemoveJsonSubset,
+ formatJson,
+ getOperationJsonPayload,
+ getOperationPreviousContent,
+ getOperationPreviousJson,
+ getOperationTextContent,
+ jsonContainsSubset,
+} = require('./install/json-ops');
const OPENCODE_BUILD_ARTIFACT = path.join('.opencode', 'dist');
const OPENCODE_BUILD_SCRIPT = path.join('scripts', 'build-opencode.js');
const OPENCODE_PLUGIN_NOT_BUILT_CODE = 'opencode-plugin-not-built';
@@@ -269,6 -259,438 +283,7 @@@ function getExpectedCopyFileContent(ope
});
}
-function isPlainObject(value) {
- return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
-}
-
-function cloneJsonValue(value) {
- if (value === undefined) {
- return undefined;
- }
-
- return JSON.parse(JSON.stringify(value));
-}
-
-function parseJsonLikeValue(value, label) {
- if (value === undefined) {
- return undefined;
- }
-
- if (typeof value === 'string') {
- try {
- return JSON.parse(value);
- } catch (error) {
- throw new Error(`Invalid ${label}: ${error.message}`);
- }
- }
-
- if (value === null || Array.isArray(value) || isPlainObject(value) || typeof value === 'number' || typeof value === 'boolean') {
- return cloneJsonValue(value);
- }
-
- throw new Error(`Invalid ${label}: expected JSON-compatible data`);
-}
-
-function getOperationTextContent(operation) {
- const candidateKeys = ['renderedContent', 'content', 'managedContent', 'expectedContent', 'templateOutput'];
-
- for (const key of candidateKeys) {
- if (typeof operation[key] === 'string') {
- return operation[key];
- }
- }
-
- return null;
-}
-
-function getOperationJsonPayload(operation) {
- const candidateKeys = ['mergePayload', 'managedPayload', 'payload', 'value', 'expectedValue'];
-
- for (const key of candidateKeys) {
- if (operation[key] !== undefined) {
- return parseJsonLikeValue(operation[key], `${operation.kind}.${key}`);
- }
- }
-
- return undefined;
-}
-
-function getOperationPreviousContent(operation) {
- const candidateKeys = ['previousContent', 'originalContent', 'backupContent'];
-
- for (const key of candidateKeys) {
- if (typeof operation[key] === 'string') {
- return operation[key];
- }
- }
-
- return null;
-}
-
-function getOperationPreviousJson(operation) {
- const candidateKeys = ['previousValue', 'previousJson', 'originalValue'];
-
- for (const key of candidateKeys) {
- if (operation[key] !== undefined) {
- return parseJsonLikeValue(operation[key], `${operation.kind}.${key}`);
- }
- }
-
- return undefined;
-}
-
-function formatJson(value) {
- return `${JSON.stringify(value, null, 2)}\n`;
-}
-
-function getManagedDestination(
- destinationPath,
- trustedRoot,
- action,
- { allowFinalSymlink = false } = {}
-) {
- if (!destinationPath || typeof destinationPath !== 'string') {
- throw new Error(`Refusing to ${action}: missing destination path.`);
- }
-
- const canonicalRoot = assertWithinTrustedRoot(trustedRoot, trustedRoot, action);
- const resolvedDestination = path.resolve(destinationPath);
- const canonicalParent = assertWithinTrustedRoot(
- path.dirname(resolvedDestination),
- canonicalRoot,
- action
- );
- const managedPath = path.join(canonicalParent, path.basename(resolvedDestination));
- let stat = null;
-
- try {
- stat = fs.lstatSync(managedPath);
- } catch (error) {
- if (!error || (error.code !== 'ENOENT' && error.code !== 'ENOTDIR')) {
- throw error;
- }
- }
-
- if (stat && stat.isSymbolicLink() && !allowFinalSymlink) {
- const error = new Error(
- `Refusing to ${action}: managed destination is a final symlink.`
- );
- error.code = 'ECC_FINAL_DESTINATION_SYMLINK';
- throw error;
- }
-
- return {
- canonicalRoot,
- exists: stat !== null,
- isFinalSymlink: Boolean(stat && stat.isSymbolicLink()),
- managedPath
- };
-}
-
-function ensureContainedParentDir(destinationPath, trustedRoot, action) {
- const initialDestination = getManagedDestination(
- destinationPath,
- trustedRoot,
- action
- );
- const { canonicalRoot, managedPath } = initialDestination;
- const canonicalParent = path.dirname(managedPath);
- const relativeParent = path.relative(canonicalRoot, canonicalParent);
- const pathSegments = relativeParent
- ? relativeParent.split(path.sep).filter(Boolean)
- : [];
- let currentPath = canonicalRoot;
-
- for (const segment of pathSegments) {
- const validatedParent = assertWithinTrustedRoot(currentPath, canonicalRoot, action);
- const nextPath = path.join(validatedParent, segment);
- try {
- fs.mkdirSync(nextPath);
- } catch (error) {
- if (!error || error.code !== 'EEXIST') {
- throw error;
- }
- }
-
- const validatedNext = assertWithinTrustedRoot(nextPath, canonicalRoot, action);
- const nextStat = fs.lstatSync(validatedNext);
- if (!nextStat.isDirectory() || nextStat.isSymbolicLink()) {
- throw new Error(`Refusing to ${action}: destination parent is not a trusted directory.`);
- }
- currentPath = validatedNext;
- }
-
- return getManagedDestination(managedPath, canonicalRoot, action).managedPath;
-}
-
-function prepareContainedWriteDestination(destinationPath, trustedRoot, action) {
- return ensureContainedParentDir(destinationPath, trustedRoot, action);
-}
-
-function getContainedExistingPath(
- destinationPath,
- trustedRoot,
- action,
- { allowFinalSymlink = false } = {}
-) {
- const initialDestination = getManagedDestination(
- destinationPath,
- trustedRoot,
- action,
- { allowFinalSymlink }
- );
- const followsToExistingPath = fs.existsSync(initialDestination.managedPath);
- if (!followsToExistingPath && !initialDestination.isFinalSymlink) {
- return null;
- }
-
- const finalDestination = getManagedDestination(
- initialDestination.managedPath,
- trustedRoot,
- action,
- { allowFinalSymlink }
- );
- return finalDestination.exists ? finalDestination.managedPath : null;
-}
-
-function hasSameFileIdentity(leftStat, rightStat) {
- return leftStat.dev === rightStat.dev && leftStat.ino === rightStat.ino;
-}
-
-function createChangedDestinationError(action) {
- return new Error(
- `Refusing to ${action}: managed destination changed during the write.`
- );
-}
-
-function writeFileNoFollow(filePath, content, mode, trustedRoot, action, writeOptions = {}) {
- return guardedWriteFile(filePath, content, {
- ...writeOptions,
- mode,
- action,
- validateDestination(destinationPath) {
- return getManagedDestination(destinationPath, trustedRoot, action).managedPath;
- },
- });
-}
-
-function readFileWithMetadataNoFollow(filePath, encoding) {
- const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0);
- const fileDescriptor = fs.openSync(filePath, flags);
-
- try {
- const stat = fs.fstatSync(fileDescriptor);
- if (!stat.isFile()) {
- throw new Error(`Refusing to read non-file path: ${filePath}`);
- }
- return {
- content: fs.readFileSync(fileDescriptor, encoding),
- mode: stat.mode,
- };
- } finally {
- fs.closeSync(fileDescriptor);
- }
-}
-
-function readFileNoFollow(filePath, encoding) {
- return readFileWithMetadataNoFollow(filePath, encoding).content;
-}
-
-function readJsonNoFollow(filePath) {
- return JSON.parse(readFileNoFollow(filePath, 'utf8'));
-}
-
-/**
- * Read hooks.json and merge in hooks/hooks.metadata.json without following
- * symlinks. The sidecar holds the stable matcher ids that hooks.json cannot
- * carry, because Claude Code reports unknown keys when the plugin loads. A
- * sidecar that does not line up with hooks.json is rejected before repair can
- * reconcile matchers under the wrong ids.
- *
- * @param {string} hooksPath - Path to the source hooks.json.
- * @returns {object} the hooks configuration with ids and descriptions restored.
- */
-function readHooksConfigNoFollow(hooksPath) {
- const hooksConfig = readJsonNoFollow(hooksPath);
- const metadataPath = metadataPathFor(hooksPath);
- if (!fs.existsSync(metadataPath)) {
- return hooksConfig;
- }
- return mergeHooksMetadata(hooksConfig, readJsonNoFollow(metadataPath), hooksPath);
-}
-
-function assertClaudeSettingsDestination(operation, trustedRoot, target = null) {
- if (target && target !== 'claude' && target !== 'claude-project') {
- throw new Error('Refusing to manage Claude hooks for a non-Claude target.');
- }
- assertClaudeSettingsPath(operation.destinationPath, trustedRoot);
-}
-
-function writeContainedFile(destinationPath, content, trustedRoot, action, mode, writeOptions) {
- const preparedDestination = prepareContainedWriteDestination(destinationPath, trustedRoot, action);
- const finalDestination = getManagedDestination(
- preparedDestination,
- trustedRoot,
- action
- ).managedPath;
- writeFileNoFollow(
- finalDestination,
- content,
- mode,
- trustedRoot,
- action,
- writeOptions
- );
- return finalDestination;
-}
-
-function copyContainedFile(sourcePath, destinationPath, trustedRoot, action) {
- const source = readFileWithMetadataNoFollow(sourcePath);
- return writeContainedFile(
- destinationPath,
- source.content,
- trustedRoot,
- action,
- source.mode & 0o777
- );
-}
-
-function removeContainedPath(destinationPath, trustedRoot, action, options = {}) {
- const existingDestination = getContainedExistingPath(
- destinationPath,
- trustedRoot,
- action,
- { allowFinalSymlink: true }
- );
- if (!existingDestination) {
- return null;
- }
-
- const managedDestination = getManagedDestination(
- existingDestination,
- trustedRoot,
- action,
- { allowFinalSymlink: true }
- );
- const finalDestination = managedDestination.managedPath;
- const expectedStat = fs.lstatSync(finalDestination, { bigint: true });
- const quarantineDir = fs.mkdtempSync(path.join(
- path.dirname(managedDestination.canonicalRoot),
- '.ecc-remove-'
- ));
- const quarantinePath = path.join(quarantineDir, path.basename(finalDestination));
-
- try {
- fs.renameSync(finalDestination, quarantinePath);
- } catch (error) {
- fs.rmdirSync(quarantineDir);
- throw error;
- }
-
- const quarantinedStat = fs.lstatSync(quarantinePath, { bigint: true });
- if (!hasSameFileIdentity(expectedStat, quarantinedStat)) {
- try {
- fs.renameSync(quarantinePath, finalDestination);
- fs.rmdirSync(quarantineDir);
- } catch (_restoreError) {
- throw new Error(
- `Refusing to ${action}: managed destination changed before removal; replacement preserved at ${quarantinePath}.`
- );
- }
- throw createChangedDestinationError(action);
- }
-
- if (quarantinedStat.isDirectory() && !options.recursive) {
- fs.rmdirSync(quarantinePath);
- } else {
- fs.rmSync(quarantinePath, options);
- }
- fs.rmdirSync(quarantineDir);
- return finalDestination;
-}
-
-function deepMergeJson(baseValue, patchValue) {
- if (!isPlainObject(baseValue) || !isPlainObject(patchValue)) {
- return cloneJsonValue(patchValue);
- }
-
- const merged = { ...baseValue };
- for (const [key, value] of Object.entries(patchValue)) {
- if (isPlainObject(value) && isPlainObject(merged[key])) {
- merged[key] = deepMergeJson(merged[key], value);
- } else {
- merged[key] = cloneJsonValue(value);
- }
- }
- return merged;
-}
-
-function jsonContainsSubset(actualValue, expectedValue) {
- if (isPlainObject(expectedValue)) {
- if (!isPlainObject(actualValue)) {
- return false;
- }
-
- return Object.entries(expectedValue).every(([key, value]) => Object.prototype.hasOwnProperty.call(actualValue, key) && jsonContainsSubset(actualValue[key], value));
- }
-
- if (Array.isArray(expectedValue)) {
- if (!Array.isArray(actualValue) || actualValue.length !== expectedValue.length) {
- return false;
- }
-
- return expectedValue.every((item, index) => jsonContainsSubset(actualValue[index], item));
- }
-
- return actualValue === expectedValue;
-}
-
-const JSON_REMOVE_SENTINEL = Symbol('json-remove');
-
-function deepRemoveJsonSubset(currentValue, managedValue) {
- if (isPlainObject(managedValue)) {
- if (!isPlainObject(currentValue)) {
- return currentValue;
- }
-
- const nextValue = { ...currentValue };
- for (const [key, value] of Object.entries(managedValue)) {
- if (!Object.prototype.hasOwnProperty.call(nextValue, key)) {
- continue;
- }
-
- if (isPlainObject(value)) {
- const nestedValue = deepRemoveJsonSubset(nextValue[key], value);
- if (nestedValue === JSON_REMOVE_SENTINEL) {
- delete nextValue[key];
- } else {
- nextValue[key] = nestedValue;
- }
- continue;
- }
-
- if (Array.isArray(value)) {
- if (Array.isArray(nextValue[key]) && jsonContainsSubset(nextValue[key], value)) {
- delete nextValue[key];
- }
- continue;
- }
-
- if (nextValue[key] === value) {
- delete nextValue[key];
- }
- }
-
- return Object.keys(nextValue).length === 0 ? JSON_REMOVE_SENTINEL : nextValue;
- }
-
- if (Array.isArray(managedValue)) {
- return jsonContainsSubset(currentValue, managedValue) ? JSON_REMOVE_SENTINEL : currentValue;
- }
-
- return currentValue === managedValue ? JSON_REMOVE_SENTINEL : currentValue;
-}
+
function hydrateRecordedOperations(repoRoot, operations, trustedRoot) {
return operations.map(operation => {
if (operation.kind === 'update-claude-settings') {
diff --cc scripts/lib/install/contained-fs.js
index db1cbbfda,000000000..3b2db7161
mode 100644,000000..100644
--- a/scripts/lib/install/contained-fs.js
+++ b/scripts/lib/install/contained-fs.js
@@@ -1,370 -1,0 +1,319 @@@
+const fs = require('fs');
+const path = require('path');
+const { assertWithinTrustedRoot } = require('../path-safety');
+const { mergeHooksMetadata, metadataPathFor } = require('../hooks-config');
++const { writeFileNoFollow: guardedWriteFile } = require('./guarded-write');
+const { assertClaudeSettingsPath } = require('./claude-settings');
+
+function getManagedDestination(
+ destinationPath,
+ trustedRoot,
+ action,
+ { allowFinalSymlink = false } = {}
+) {
+ if (!destinationPath || typeof destinationPath !== 'string') {
+ throw new Error(`Refusing to ${action}: missing destination path.`);
+ }
+
+ const canonicalRoot = assertWithinTrustedRoot(trustedRoot, trustedRoot, action);
+ const resolvedDestination = path.resolve(destinationPath);
+ const canonicalParent = assertWithinTrustedRoot(
+ path.dirname(resolvedDestination),
+ canonicalRoot,
+ action
+ );
+ const managedPath = path.join(canonicalParent, path.basename(resolvedDestination));
+ let stat = null;
+
+ try {
+ stat = fs.lstatSync(managedPath);
+ } catch (error) {
+ if (!error || (error.code !== 'ENOENT' && error.code !== 'ENOTDIR')) {
+ throw error;
+ }
+ }
+
+ if (stat && stat.isSymbolicLink() && !allowFinalSymlink) {
+ const error = new Error(
+ `Refusing to ${action}: managed destination is a final symlink.`
+ );
+ error.code = 'ECC_FINAL_DESTINATION_SYMLINK';
+ throw error;
+ }
+
+ return {
+ canonicalRoot,
+ exists: stat !== null,
+ isFinalSymlink: Boolean(stat && stat.isSymbolicLink()),
+ managedPath
+ };
+}
+
+function ensureContainedParentDir(destinationPath, trustedRoot, action) {
+ const initialDestination = getManagedDestination(
+ destinationPath,
+ trustedRoot,
+ action
+ );
+ const { canonicalRoot, managedPath } = initialDestination;
+ const canonicalParent = path.dirname(managedPath);
+ const relativeParent = path.relative(canonicalRoot, canonicalParent);
+ const pathSegments = relativeParent
+ ? relativeParent.split(path.sep).filter(Boolean)
+ : [];
+ let currentPath = canonicalRoot;
+
+ for (const segment of pathSegments) {
+ const validatedParent = assertWithinTrustedRoot(currentPath, canonicalRoot, action);
+ const nextPath = path.join(validatedParent, segment);
+ try {
+ fs.mkdirSync(nextPath);
+ } catch (error) {
+ if (!error || error.code !== 'EEXIST') {
+ throw error;
+ }
+ }
+
+ const validatedNext = assertWithinTrustedRoot(nextPath, canonicalRoot, action);
+ const nextStat = fs.lstatSync(validatedNext);
+ if (!nextStat.isDirectory() || nextStat.isSymbolicLink()) {
+ throw new Error(`Refusing to ${action}: destination parent is not a trusted directory.`);
+ }
+ currentPath = validatedNext;
+ }
+
+ return getManagedDestination(managedPath, canonicalRoot, action).managedPath;
+}
+
+function prepareContainedWriteDestination(destinationPath, trustedRoot, action) {
+ return ensureContainedParentDir(destinationPath, trustedRoot, action);
+}
+
+function getContainedExistingPath(
+ destinationPath,
+ trustedRoot,
+ action,
+ { allowFinalSymlink = false } = {}
+) {
+ const initialDestination = getManagedDestination(
+ destinationPath,
+ trustedRoot,
+ action,
+ { allowFinalSymlink }
+ );
+ const followsToExistingPath = fs.existsSync(initialDestination.managedPath);
+ if (!followsToExistingPath && !initialDestination.isFinalSymlink) {
+ return null;
+ }
+
+ const finalDestination = getManagedDestination(
+ initialDestination.managedPath,
+ trustedRoot,
+ action,
+ { allowFinalSymlink }
+ );
+ return finalDestination.exists ? finalDestination.managedPath : null;
+}
+
+function hasSameFileIdentity(leftStat, rightStat) {
+ return leftStat.dev === rightStat.dev && leftStat.ino === rightStat.ino;
+}
+
+function createChangedDestinationError(action) {
+ return new Error(
+ `Refusing to ${action}: managed destination changed during the write.`
+ );
+}
+
- function getStableParentStat(filePath, action) {
- const parentStat = fs.lstatSync(path.dirname(filePath));
- if (!parentStat.isDirectory() || parentStat.isSymbolicLink()) {
- throw createChangedDestinationError(action);
- }
- return parentStat;
- }
-
- function assertPinnedWriteDestination(
- filePath,
- fileDescriptor,
- expectedParentStat,
- trustedRoot,
- action
- ) {
- const liveDestination = getManagedDestination(filePath, trustedRoot, action);
- if (path.resolve(liveDestination.managedPath) !== path.resolve(filePath)) {
- throw createChangedDestinationError(action);
- }
-
- const liveParentStat = getStableParentStat(filePath, action);
- if (!hasSameFileIdentity(expectedParentStat, liveParentStat)) {
- throw createChangedDestinationError(action);
- }
-
- const descriptorStat = fs.fstatSync(fileDescriptor);
- const livePathStat = fs.lstatSync(liveDestination.managedPath);
- if (
- !descriptorStat.isFile()
- || !livePathStat.isFile()
- || livePathStat.isSymbolicLink()
- || !hasSameFileIdentity(descriptorStat, livePathStat)
- ) {
- throw createChangedDestinationError(action);
- }
- }
-
- function writeFileNoFollow(filePath, content, mode, trustedRoot, action) {
- const expectedParentStat = getStableParentStat(filePath, action);
- const flags = fs.constants.O_WRONLY
- | fs.constants.O_CREAT
- | (fs.constants.O_NOFOLLOW || 0);
- const fileDescriptor = fs.openSync(filePath, flags, mode);
-
- try {
- assertPinnedWriteDestination(
- filePath,
- fileDescriptor,
- expectedParentStat,
- trustedRoot,
- action
- );
- fs.ftruncateSync(fileDescriptor, 0);
- fs.writeFileSync(fileDescriptor, content);
- if (mode !== undefined) {
- fs.fchmodSync(fileDescriptor, mode);
- }
- } finally {
- fs.closeSync(fileDescriptor);
- }
++function writeFileNoFollow(filePath, content, mode, trustedRoot, action, writeOptions = {}) {
++ return guardedWriteFile(filePath, content, {
++ ...writeOptions,
++ mode,
++ action,
++ validateDestination(destinationPath) {
++ return getManagedDestination(destinationPath, trustedRoot, action).managedPath;
++ },
++ });
+}
+
+function readFileWithMetadataNoFollow(filePath, encoding) {
+ const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0);
+ const fileDescriptor = fs.openSync(filePath, flags);
+
+ try {
+ const stat = fs.fstatSync(fileDescriptor);
+ if (!stat.isFile()) {
+ throw new Error(`Refusing to read non-file path: ${filePath}`);
+ }
+ return {
+ content: fs.readFileSync(fileDescriptor, encoding),
+ mode: stat.mode,
+ };
+ } finally {
+ fs.closeSync(fileDescriptor);
+ }
+}
+
+function readFileNoFollow(filePath, encoding) {
+ return readFileWithMetadataNoFollow(filePath, encoding).content;
+}
+
+function readJsonNoFollow(filePath) {
+ return JSON.parse(readFileNoFollow(filePath, 'utf8'));
+}
+
+function readHooksConfigNoFollow(hooksPath) {
+ const hooksConfig = readJsonNoFollow(hooksPath);
+ const metadataPath = metadataPathFor(hooksPath);
+ if (!fs.existsSync(metadataPath)) {
+ return hooksConfig;
+ }
+ return mergeHooksMetadata(hooksConfig, readJsonNoFollow(metadataPath), hooksPath);
+}
+
+function assertClaudeSettingsDestination(operation, trustedRoot, target = null) {
+ if (target && target !== 'claude' && target !== 'claude-project') {
+ throw new Error('Refusing to manage Claude hooks for a non-Claude target.');
+ }
+ assertClaudeSettingsPath(operation.destinationPath, trustedRoot);
+}
+
- function writeContainedFile(destinationPath, content, trustedRoot, action, mode) {
++function writeContainedFile(destinationPath, content, trustedRoot, action, mode, writeOptions) {
+ const preparedDestination = prepareContainedWriteDestination(destinationPath, trustedRoot, action);
+ const finalDestination = getManagedDestination(
+ preparedDestination,
+ trustedRoot,
+ action
+ ).managedPath;
+ writeFileNoFollow(
+ finalDestination,
+ content,
+ mode,
+ trustedRoot,
- action
++ action,
++ writeOptions
+ );
+ return finalDestination;
+}
+
+function copyContainedFile(sourcePath, destinationPath, trustedRoot, action) {
+ const source = readFileWithMetadataNoFollow(sourcePath);
+ return writeContainedFile(
+ destinationPath,
+ source.content,
+ trustedRoot,
+ action,
+ source.mode & 0o777
+ );
+}
+
+function removeContainedPath(destinationPath, trustedRoot, action, options = {}) {
+ const existingDestination = getContainedExistingPath(
+ destinationPath,
+ trustedRoot,
+ action,
+ { allowFinalSymlink: true }
+ );
+ if (!existingDestination) {
+ return null;
+ }
+
+ const managedDestination = getManagedDestination(
+ existingDestination,
+ trustedRoot,
+ action,
+ { allowFinalSymlink: true }
+ );
+ const finalDestination = managedDestination.managedPath;
+ const expectedStat = fs.lstatSync(finalDestination, { bigint: true });
+ const quarantineDir = fs.mkdtempSync(path.join(
+ path.dirname(managedDestination.canonicalRoot),
+ '.ecc-remove-'
+ ));
+ const quarantinePath = path.join(quarantineDir, path.basename(finalDestination));
+
+ try {
+ fs.renameSync(finalDestination, quarantinePath);
+ } catch (error) {
+ fs.rmdirSync(quarantineDir);
+ throw error;
+ }
+
+ const quarantinedStat = fs.lstatSync(quarantinePath, { bigint: true });
+ if (!hasSameFileIdentity(expectedStat, quarantinedStat)) {
+ try {
+ fs.renameSync(quarantinePath, finalDestination);
+ fs.rmdirSync(quarantineDir);
+ } catch (_restoreError) {
+ throw new Error(
+ `Refusing to ${action}: managed destination changed before removal; replacement preserved at ${quarantinePath}.`
+ );
+ }
+ throw createChangedDestinationError(action);
+ }
+
+ if (quarantinedStat.isDirectory() && !options.recursive) {
+ fs.rmdirSync(quarantinePath);
+ } else {
+ fs.rmSync(quarantinePath, options);
+ }
+ fs.rmdirSync(quarantineDir);
+ return finalDestination;
+}
+
+function cleanupEmptyParentDirs(filePath, stopAt) {
+ const trustedStopAt = assertWithinTrustedRoot(stopAt, stopAt, 'clean up');
+ const trustedFilePath = assertWithinTrustedRoot(filePath, trustedStopAt, 'clean up');
+ let currentPath = path.dirname(trustedFilePath);
+
+ while (currentPath) {
+ const relativePath = path.relative(trustedStopAt, currentPath);
+ const isContained = relativePath !== '..'
+ && !relativePath.startsWith(`..${path.sep}`)
+ && !path.isAbsolute(relativePath);
+ if (!isContained || relativePath === '') {
+ break;
+ }
+
+ let validatedPath = assertWithinTrustedRoot(currentPath, trustedStopAt, 'clean up');
+ if (!fs.existsSync(validatedPath)) {
+ currentPath = path.dirname(validatedPath);
+ continue;
+ }
+
+ validatedPath = assertWithinTrustedRoot(validatedPath, trustedStopAt, 'clean up');
+ const stat = fs.lstatSync(validatedPath);
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
+ break;
+ }
+
+ validatedPath = assertWithinTrustedRoot(validatedPath, trustedStopAt, 'clean up');
+ if (fs.readdirSync(validatedPath).length > 0) {
+ break;
+ }
+
+ const finalPath = assertWithinTrustedRoot(validatedPath, trustedStopAt, 'clean up');
+ const removedPath = removeContainedPath(finalPath, trustedStopAt, 'clean up');
+ if (!removedPath) break;
+ currentPath = path.dirname(removedPath);
+ }
+}
+
+module.exports = {
+ assertClaudeSettingsDestination,
- assertPinnedWriteDestination,
+ cleanupEmptyParentDirs,
+ copyContainedFile,
+ createChangedDestinationError,
+ ensureContainedParentDir,
+ getContainedExistingPath,
+ getManagedDestination,
- getStableParentStat,
+ hasSameFileIdentity,
+ prepareContainedWriteDestination,
+ readFileNoFollow,
+ readFileWithMetadataNoFollow,
+ readHooksConfigNoFollow,
+ readJsonNoFollow,
+ removeContainedPath,
+ writeContainedFile,
- writeFileNoFollow,
++ writeFileNoFollow
+};
diff --cc scripts/lib/install/json-ops.js
index f5aad032d,000000000..b691be790
mode 100644,000000..100644
--- a/scripts/lib/install/json-ops.js
+++ b/scripts/lib/install/json-ops.js
@@@ -1,180 -1,0 +1,180 @@@
+function isPlainObject(value) {
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
+}
+
+function cloneJsonValue(value) {
+ if (value === undefined) {
+ return undefined;
+ }
+
+ return JSON.parse(JSON.stringify(value));
+}
+
+function parseJsonLikeValue(value, label) {
+ if (value === undefined) {
+ return undefined;
+ }
+
+ if (typeof value === 'string') {
+ try {
+ return JSON.parse(value);
+ } catch (error) {
+ throw new Error(`Invalid ${label}: ${error.message}`);
+ }
+ }
+
+ if (value === null || Array.isArray(value) || isPlainObject(value) || typeof value === 'number' || typeof value === 'boolean') {
+ return cloneJsonValue(value);
+ }
+
+ throw new Error(`Invalid ${label}: expected JSON-compatible data`);
+}
+
+function getOperationTextContent(operation) {
+ const candidateKeys = ['renderedContent', 'content', 'managedContent', 'expectedContent', 'templateOutput'];
+
+ for (const key of candidateKeys) {
+ if (typeof operation[key] === 'string') {
+ return operation[key];
+ }
+ }
+
+ return null;
+}
+
+function getOperationJsonPayload(operation) {
+ const candidateKeys = ['mergePayload', 'managedPayload', 'payload', 'value', 'expectedValue'];
+
+ for (const key of candidateKeys) {
+ if (operation[key] !== undefined) {
+ return parseJsonLikeValue(operation[key], `${operation.kind}.${key}`);
+ }
+ }
+
+ return undefined;
+}
+
+function getOperationPreviousContent(operation) {
+ const candidateKeys = ['previousContent', 'originalContent', 'backupContent'];
+
+ for (const key of candidateKeys) {
+ if (typeof operation[key] === 'string') {
+ return operation[key];
+ }
+ }
+
+ return null;
+}
+
+function getOperationPreviousJson(operation) {
+ const candidateKeys = ['previousValue', 'previousJson', 'originalValue'];
+
+ for (const key of candidateKeys) {
+ if (operation[key] !== undefined) {
+ return parseJsonLikeValue(operation[key], `${operation.kind}.${key}`);
+ }
+ }
+
+ return undefined;
+}
+
+function formatJson(value) {
+ return `${JSON.stringify(value, null, 2)}\n`;
+}
+
+function deepMergeJson(baseValue, patchValue) {
+ if (!isPlainObject(baseValue) || !isPlainObject(patchValue)) {
+ return cloneJsonValue(patchValue);
+ }
+
+ const merged = { ...baseValue };
+ for (const [key, value] of Object.entries(patchValue)) {
+ if (isPlainObject(value) && isPlainObject(merged[key])) {
+ merged[key] = deepMergeJson(merged[key], value);
+ } else {
+ merged[key] = cloneJsonValue(value);
+ }
+ }
+ return merged;
+}
+
+function jsonContainsSubset(actualValue, expectedValue) {
+ if (isPlainObject(expectedValue)) {
+ if (!isPlainObject(actualValue)) {
+ return false;
+ }
+
+ return Object.entries(expectedValue).every(([key, value]) => Object.prototype.hasOwnProperty.call(actualValue, key) && jsonContainsSubset(actualValue[key], value));
+ }
+
+ if (Array.isArray(expectedValue)) {
+ if (!Array.isArray(actualValue) || actualValue.length !== expectedValue.length) {
+ return false;
+ }
+
+ return expectedValue.every((item, index) => jsonContainsSubset(actualValue[index], item));
+ }
+
+ return actualValue === expectedValue;
+}
+
- const JSON_REMOVE_SENTINEL = Symbol('json-remove');
-
+function deepRemoveJsonSubset(currentValue, managedValue) {
+ if (isPlainObject(managedValue)) {
+ if (!isPlainObject(currentValue)) {
+ return currentValue;
+ }
+
+ const nextValue = { ...currentValue };
+ for (const [key, value] of Object.entries(managedValue)) {
+ if (!Object.prototype.hasOwnProperty.call(nextValue, key)) {
+ continue;
+ }
+
+ if (isPlainObject(value)) {
+ const nestedValue = deepRemoveJsonSubset(nextValue[key], value);
+ if (nestedValue === JSON_REMOVE_SENTINEL) {
+ delete nextValue[key];
+ } else {
+ nextValue[key] = nestedValue;
+ }
+ continue;
+ }
+
+ if (Array.isArray(value)) {
+ if (Array.isArray(nextValue[key]) && jsonContainsSubset(nextValue[key], value)) {
+ delete nextValue[key];
+ }
+ continue;
+ }
+
+ if (nextValue[key] === value) {
+ delete nextValue[key];
+ }
+ }
+
+ return Object.keys(nextValue).length === 0 ? JSON_REMOVE_SENTINEL : nextValue;
+ }
+
+ if (Array.isArray(managedValue)) {
+ return jsonContainsSubset(currentValue, managedValue) ? JSON_REMOVE_SENTINEL : currentValue;
+ }
+
+ return currentValue === managedValue ? JSON_REMOVE_SENTINEL : currentValue;
+}
+
++const JSON_REMOVE_SENTINEL = Symbol('json-remove');
++
+module.exports = {
+ JSON_REMOVE_SENTINEL,
+ cloneJsonValue,
+ deepMergeJson,
+ deepRemoveJsonSubset,
+ formatJson,
+ getOperationJsonPayload,
+ getOperationPreviousContent,
+ getOperationPreviousJson,
+ getOperationTextContent,
+ isPlainObject,
+ jsonContainsSubset,
- parseJsonLikeValue,
++ parseJsonLikeValue
+};