@ornexus/neocortex 4.60.72 → 4.60.73
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/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +24 -24
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/adapters/adapter-registry.js +108 -1
- package/packages/client/dist/adapters/antigravity-adapter.js +77 -2
- package/packages/client/dist/adapters/claude-code-adapter.js +79 -3
- package/packages/client/dist/adapters/codex-adapter.js +80 -2
- package/packages/client/dist/adapters/cursor-adapter.js +115 -4
- package/packages/client/dist/adapters/gemini-adapter.js +71 -2
- package/packages/client/dist/adapters/grok-adapter.js +42 -2
- package/packages/client/dist/adapters/index.js +22 -1
- package/packages/client/dist/adapters/platform-detector.js +212 -1
- package/packages/client/dist/adapters/target-adapter.js +12 -0
- package/packages/client/dist/adapters/vscode-adapter.js +72 -2
- package/packages/client/dist/agent/refresh-stubs.js +417 -2
- package/packages/client/dist/agent/update-agent-yaml.js +102 -1
- package/packages/client/dist/agent/update-description.js +251 -1
- package/packages/client/dist/cache/crypto-utils.js +78 -1
- package/packages/client/dist/cache/encrypted-cache.js +108 -1
- package/packages/client/dist/cache/in-memory-asset-cache.js +73 -1
- package/packages/client/dist/cache/index.js +13 -1
- package/packages/client/dist/cache/protected-pi-boundary.js +44 -1
- package/packages/client/dist/checkpoint/checkpoint-client-reader.js +127 -2
- package/packages/client/dist/checkpoint/index.js +11 -1
- package/packages/client/dist/checkpoint/shared-checkpoint-types.js +32 -1
- package/packages/client/dist/cli.js +358 -5
- package/packages/client/dist/commands/activate.js +394 -8
- package/packages/client/dist/commands/architecture-answers.js +274 -7
- package/packages/client/dist/commands/architecture-memory-terminal.js +253 -4
- package/packages/client/dist/commands/architecture-non-ui-continuation.js +100 -1
- package/packages/client/dist/commands/architecture-root-binding.js +51 -1
- package/packages/client/dist/commands/cache-status.js +112 -2
- package/packages/client/dist/commands/config.js +88 -1
- package/packages/client/dist/commands/doctor.js +635 -2
- package/packages/client/dist/commands/invoke.js +7200 -143
- package/packages/client/dist/commands/legacy-epic-terminal.js +71 -1
- package/packages/client/dist/commands/legacy-story-branch.js +96 -1
- package/packages/client/dist/commands/legacy-story-pr.js +276 -1
- package/packages/client/dist/commands/mutation-qa-checkpoint.js +285 -5
- package/packages/client/dist/commands/mutation-qa-gate.js +54 -1
- package/packages/client/dist/commands/mutation-qa-git.js +41 -1
- package/packages/client/dist/commands/mutation-qa-policy.js +102 -1
- package/packages/client/dist/commands/mutation-qa-run.js +219 -3
- package/packages/client/dist/commands/mutation-qa-verdict.js +149 -1
- package/packages/client/dist/commands/mutation-qa.js +220 -1
- package/packages/client/dist/commands/native-agent.js +136 -2
- package/packages/client/dist/commands/planning-diagnosis.js +43 -1
- package/packages/client/dist/commands/planning-generation.js +53 -1
- package/packages/client/dist/commands/planning-memory.js +40 -1
- package/packages/client/dist/commands/planning-research.js +42 -1
- package/packages/client/dist/commands/private-session.js +75 -1
- package/packages/client/dist/commands/property-qa.js +139 -1
- package/packages/client/dist/commands/qa-control.js +16 -1
- package/packages/client/dist/commands/qa-scan-browser-launch.js +55 -1
- package/packages/client/dist/commands/qa-scan-browser-route.js +28 -1
- package/packages/client/dist/commands/qa-scan-capture.js +663 -5
- package/packages/client/dist/commands/qa-scan-discovery.js +376 -3
- package/packages/client/dist/commands/qa-scan-review.js +826 -5
- package/packages/client/dist/commands/qa-synthetic-backend-capture.js +266 -1
- package/packages/client/dist/commands/qa-synthetic-backend-review.js +297 -1
- package/packages/client/dist/commands/qa-synthetic-backend.js +340 -2
- package/packages/client/dist/commands/qa-synthetic-broker-port.js +85 -1
- package/packages/client/dist/commands/qa-synthetic-browser.js +39 -1
- package/packages/client/dist/commands/refactor-characterization.js +671 -21
- package/packages/client/dist/commands/refactor-commit.js +399 -13
- package/packages/client/dist/commands/refactor-control.js +142 -3
- package/packages/client/dist/commands/refactor-cpp-assertions.js +93 -3
- package/packages/client/dist/commands/refactor-review.js +283 -5
- package/packages/client/dist/commands/refactor-root.js +588 -7
- package/packages/client/dist/commands/refresh-memory.js +156 -3
- package/packages/client/dist/commands/shared-architecture-non-ui.js +24 -1
- package/packages/client/dist/commands/story-checkpoint.js +171 -1
- package/packages/client/dist/config/profile-directory.js +13 -1
- package/packages/client/dist/config/resolver-selection.js +278 -1
- package/packages/client/dist/config/secure-config.js +281 -12
- package/packages/client/dist/config.js +223 -2
- package/packages/client/dist/constants.js +25 -1
- package/packages/client/dist/context/context-collector.js +222 -2
- package/packages/client/dist/context/context-sanitizer.js +145 -1
- package/packages/client/dist/continuity/autonomous-governance.js +285 -1
- package/packages/client/dist/continuity/continuity-client-state-store.js +1587 -1
- package/packages/client/dist/continuity/invoke-hooks.js +129 -1
- package/packages/client/dist/continuity/migrations/001-initial-schema.js +12 -2
- package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +12 -2
- package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +12 -2
- package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +12 -2
- package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +12 -2
- package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +10 -2
- package/packages/client/dist/continuity/native-agent-store.js +69 -1
- package/packages/client/dist/continuity/native-agent-types.js +90 -1
- package/packages/client/dist/continuity/outbox.js +117 -1
- package/packages/client/dist/continuity/runner-bootstrap-policy.js +172 -1
- package/packages/client/dist/continuity/sqlite-store.d.ts +22 -1
- package/packages/client/dist/continuity/sqlite-store.js +2612 -81
- package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
- package/packages/client/dist/errors/error-messages.js +228 -2
- package/packages/client/dist/errors/frontmatter-diagnostics.js +125 -1
- package/packages/client/dist/evidence/collector.js +347 -1
- package/packages/client/dist/evidence/index.js +1 -1
- package/packages/client/dist/evidence/types.js +2 -0
- package/packages/client/dist/fs/atomic-state-replace.js +152 -1
- package/packages/client/dist/generated/command-registry.generated.js +4076 -1
- package/packages/client/dist/generated/public-projections.generated.js +149 -1
- package/packages/client/dist/git/direct-yolo-c01-retry.js +138 -4
- package/packages/client/dist/git/direct-yolo-checkpoint.js +1234 -4
- package/packages/client/dist/git/epic-operational-state.d.ts +198 -0
- package/packages/client/dist/git/epic-operational-state.js +672 -0
- package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
- package/packages/client/dist/git/git-lifecycle-store.d.ts +9 -1
- package/packages/client/dist/git/git-lifecycle-store.js +1981 -9
- package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
- package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
- package/packages/client/dist/git/legacy-story-pr.js +3538 -70
- package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
- package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
- package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
- package/packages/client/dist/i18n/first-run.js +60 -2
- package/packages/client/dist/index.js +47 -1
- package/packages/client/dist/invocation/invoke-input.js +24 -1
- package/packages/client/dist/license/index.js +5 -1
- package/packages/client/dist/license/license-client.js +304 -1
- package/packages/client/dist/machine/fingerprint.js +163 -2
- package/packages/client/dist/machine/index.js +5 -1
- package/packages/client/dist/memory/project-memory-path-scope.js +62 -1
- package/packages/client/dist/memory/project-memory-writer.js +1007 -40
- package/packages/client/dist/memory/shared-project-memory-types.js +253 -2
- package/packages/client/dist/migrations/epic-lifecycle-backfill.d.ts +97 -0
- package/packages/client/dist/migrations/epic-lifecycle-backfill.js +1060 -0
- package/packages/client/dist/migrations/project-identity-capability.js +50 -1
- package/packages/client/dist/migrations/project-identity.js +493 -7
- package/packages/client/dist/migrations/state-json.d.ts +22 -0
- package/packages/client/dist/migrations/state-json.js +393 -4
- package/packages/client/dist/policy/architecture-policy.js +184 -2
- package/packages/client/dist/policy/index.js +7 -1
- package/packages/client/dist/policy/shared-policy-types.js +38 -0
- package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
- package/packages/client/dist/private-execution/clean-baseline.js +279 -2
- package/packages/client/dist/private-execution/codex-executor.js +574 -4
- package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
- package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
- package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
- package/packages/client/dist/private-execution/delivery.js +410 -13
- package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
- package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
- package/packages/client/dist/private-execution/implementation-validation.js +106 -2
- package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
- package/packages/client/dist/private-execution/isolated-session.js +725 -5
- package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
- package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
- package/packages/client/dist/private-execution/pact-test-source.js +258 -1
- package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
- package/packages/client/dist/private-execution/pact-write-set.js +172 -1
- package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
- package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
- package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
- package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
- package/packages/client/dist/private-execution/private-report-store.js +42 -1
- package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
- package/packages/client/dist/private-execution/property-test-choices.js +147 -3
- package/packages/client/dist/private-execution/property-test-plan.js +271 -7
- package/packages/client/dist/private-execution/property-test-review.js +258 -4
- package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
- package/packages/client/dist/private-execution/property-test-source.js +139 -1
- package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
- package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
- package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
- package/packages/client/dist/private-execution/root-memory-request.js +29 -1
- package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
- package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
- package/packages/client/dist/private-execution/session-lease.js +63 -1
- package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
- package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
- package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
- package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
- package/packages/client/dist/private-execution/ux-write-set.js +191 -2
- package/packages/client/dist/registry/registry-reconciliation.js +234 -1
- package/packages/client/dist/resilience/circuit-breaker.js +170 -1
- package/packages/client/dist/resilience/degradation-manager.js +164 -1
- package/packages/client/dist/resilience/freshness-indicator.js +100 -1
- package/packages/client/dist/resilience/index.js +8 -1
- package/packages/client/dist/resilience/recovery-detector.js +74 -1
- package/packages/client/dist/resolvers/asset-resolver.js +13 -0
- package/packages/client/dist/resolvers/local-resolver.js +255 -8
- package/packages/client/dist/resolvers/remote-resolver.js +233 -1
- package/packages/client/dist/runner/binary.js +404 -1
- package/packages/client/dist/runner/cli.js +1571 -17
- package/packages/client/dist/runner/headless/adapters.js +49 -1
- package/packages/client/dist/runner/headless/claude-code-adapter.js +79 -1
- package/packages/client/dist/runner/headless/continuous-story-workspace.js +1628 -11
- package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +69 -1
- package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +110 -2
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1236 -8
- package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +318 -2
- package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
- package/packages/client/dist/runner/headless/managed-profile.js +132 -1
- package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
- package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
- package/packages/client/dist/runner/headless/resolver.js +231 -1
- package/packages/client/dist/runner/headless/run-yolo.js +885 -1
- package/packages/client/dist/runner/headless/run-yoloop.js +2574 -2
- package/packages/client/dist/runner/headless/types.js +574 -2
- package/packages/client/dist/runner/local-console.js +396 -13
- package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
- package/packages/client/dist/runner/project-identity.js +106 -1
- package/packages/client/dist/runner/scheduler.js +995 -7
- package/packages/client/dist/runner-cli.js +18 -2
- package/packages/client/dist/state/invocation-shape.js +13 -1
- package/packages/client/dist/state/project-state-snapshot.d.ts +8 -0
- package/packages/client/dist/state/project-state-snapshot.js +1731 -1
- package/packages/client/dist/state/state-json-repair.js +785 -3
- package/packages/client/dist/state/structural-dag-projection.js +118 -1
- package/packages/client/dist/telemetry/index.js +5 -1
- package/packages/client/dist/telemetry/offline-queue.js +131 -1
- package/packages/client/dist/tier/index.js +5 -1
- package/packages/client/dist/tier/tier-aware-client.js +405 -1
- package/packages/client/dist/types/index.js +38 -1
- package/packages/client/dist/version.js +27 -1
- package/packages/client/dist/yolo/change-evidence-collector.js +126 -1
- package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
- package/packages/client/dist/yolo/spec-envelope-collector.js +184 -5
- package/packages/client/dist/yoloop/discovery-hook.js +300 -2
- package/packages/client/dist/yoloop/index.js +8 -1
- package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
- package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -1
- package/packages/client/dist/yoloop/shared-yoloop-types.d.ts +65 -1
- package/packages/client/dist/yoloop/shared-yoloop-types.js +33 -1
- package/packages/client/dist/yoloop/target-normalization.js +180 -1
- package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +8 -0
- package/packages/client/dist/yoloop/yoloop-client-state-store.js +1920 -1
- package/packages/shared/dist/yolo/spec-envelope.js +3 -6
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/opencode/neocortex-root.md +1 -1
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1 +1,347 @@
|
|
|
1
|
-
import{createHash
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { lstatSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
|
|
3
|
+
import { isAbsolute, relative, resolve } from 'node:path';
|
|
4
|
+
export const CLIENT_PROJECT_EVIDENCE_BUDGET = Object.freeze({
|
|
5
|
+
maxItems: 48,
|
|
6
|
+
maxFileBytes: 96 * 1024,
|
|
7
|
+
maxTotalBytes: 512 * 1024,
|
|
8
|
+
maxSummaryChars: 280,
|
|
9
|
+
maxEnvelopeBytes: 64 * 1024,
|
|
10
|
+
maxExclusions: 64,
|
|
11
|
+
});
|
|
12
|
+
const MAX_SCAN_ENTRIES = 512;
|
|
13
|
+
const ALLOWED_EXTENSIONS = /(?:\.tsx?|\.jsx?|\.vue|\.svelte|\.css|\.scss|\.json|\.ya?ml|\.mdx?|\.html)$/i;
|
|
14
|
+
const RICH_EXTENSIONS = /\.(?:png|jpe?g|webp)$/i;
|
|
15
|
+
const IGNORED_SEGMENTS = new Set(['.git', '.neocortex', 'node_modules', 'dist', 'build', 'coverage', 'core', 'private', 'secrets', 'credentials', 'raw-logs']);
|
|
16
|
+
const PRIVATE_CONTENT = /(?:[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|\b(?:api[-_ ]?key|license[-_ ]?key|password|secret|token)\b\s*[:=]|\b(?:sk|pk|ghp|github_pat)_[A-Za-z0-9_-]{12,}|https?:\/\/(?:localhost|127\.0\.0\.1|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(?:1[6-9]|2\d|3[01])\.\d+\.\d+|[^/\s]+\.(?:local|internal))\b|private\s+(?:prompt|workflow|customer data)|-----BEGIN [A-Z ]+PRIVATE KEY-----)/i;
|
|
17
|
+
const REDACTION_POLICIES = new Set(['metadata-only-v1', 'visual-pii-v1', 'strict-v1']);
|
|
18
|
+
function sha256(value) {
|
|
19
|
+
return createHash('sha256').update(value).digest('hex');
|
|
20
|
+
}
|
|
21
|
+
function stableJson(value) {
|
|
22
|
+
if (Array.isArray(value))
|
|
23
|
+
return `[${value.map(stableJson).join(',')}]`;
|
|
24
|
+
if (value && typeof value === 'object') {
|
|
25
|
+
const record = value;
|
|
26
|
+
return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`).join(',')}}`;
|
|
27
|
+
}
|
|
28
|
+
return JSON.stringify(value) ?? 'null';
|
|
29
|
+
}
|
|
30
|
+
function normalizePath(value) {
|
|
31
|
+
return value.trim().replace(/\\/g, '/').replace(/\/+/g, '/').replace(/^\.\//, '');
|
|
32
|
+
}
|
|
33
|
+
function pathRejection(value) {
|
|
34
|
+
const normalized = normalizePath(value);
|
|
35
|
+
if (!normalized || isAbsolute(value) || normalized.startsWith('/') || /^[a-z]:[\\/]/i.test(value))
|
|
36
|
+
return 'absolute_path_rejected';
|
|
37
|
+
if (normalized === '..' || normalized.startsWith('../') || normalized.includes('/../'))
|
|
38
|
+
return 'traversal_path_rejected';
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
function sourceId(value) {
|
|
42
|
+
return `evidence:${sha256(value).slice(0, 16)}`;
|
|
43
|
+
}
|
|
44
|
+
function excluded(value, reasonCode) {
|
|
45
|
+
return { sourceId: sourceId(value), reasonCode };
|
|
46
|
+
}
|
|
47
|
+
function isIgnored(relativePath) {
|
|
48
|
+
return normalizePath(relativePath).toLowerCase().split('/').some((segment) => segment.startsWith('.env') || IGNORED_SEGMENTS.has(segment));
|
|
49
|
+
}
|
|
50
|
+
function insideRoot(root, candidate) {
|
|
51
|
+
const rel = relative(root, candidate);
|
|
52
|
+
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
|
|
53
|
+
}
|
|
54
|
+
function inventory(root, dir, output, exclusions, maxEntries = MAX_SCAN_ENTRIES) {
|
|
55
|
+
if (output.length >= maxEntries)
|
|
56
|
+
return;
|
|
57
|
+
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
58
|
+
if (output.length >= maxEntries)
|
|
59
|
+
break;
|
|
60
|
+
const absolute = resolve(dir, entry.name);
|
|
61
|
+
const relativePath = normalizePath(relative(root, absolute));
|
|
62
|
+
if (isIgnored(relativePath))
|
|
63
|
+
continue;
|
|
64
|
+
if (entry.isSymbolicLink()) {
|
|
65
|
+
exclusions.push(excluded(relativePath, 'symlink_escape_rejected'));
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (entry.isDirectory()) {
|
|
69
|
+
inventory(root, absolute, output, exclusions, maxEntries);
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (entry.isFile() && ALLOWED_EXTENSIONS.test(entry.name))
|
|
73
|
+
output.push(relativePath);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function expandExplicitCandidate(root, candidate, output, exclusions) {
|
|
77
|
+
const rejection = pathRejection(candidate);
|
|
78
|
+
if (rejection) {
|
|
79
|
+
exclusions.push(excluded(candidate, rejection));
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
const normalized = normalizePath(candidate);
|
|
83
|
+
if (isIgnored(normalized) || PRIVATE_CONTENT.test(normalized)) {
|
|
84
|
+
exclusions.push(excluded(candidate, 'private_evidence_rejected'));
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const absolute = resolve(root, normalized);
|
|
88
|
+
if (!insideRoot(root, absolute)) {
|
|
89
|
+
exclusions.push(excluded(candidate, 'traversal_path_rejected'));
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
const stat = lstatSync(absolute);
|
|
93
|
+
if (stat.isSymbolicLink()) {
|
|
94
|
+
exclusions.push(excluded(candidate, 'symlink_escape_rejected'));
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const real = realpathSync(absolute);
|
|
98
|
+
if (!insideRoot(root, real)) {
|
|
99
|
+
exclusions.push(excluded(candidate, 'symlink_escape_rejected'));
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (stat.isDirectory()) {
|
|
103
|
+
inventory(root, real, output, exclusions);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (stat.isFile())
|
|
107
|
+
output.push(normalized);
|
|
108
|
+
}
|
|
109
|
+
function kindFor(path) {
|
|
110
|
+
const lower = path.toLowerCase();
|
|
111
|
+
if (/\.(?:stories|story)\.(?:tsx?|jsx?|mdx?)$/.test(lower) || lower.includes('/.storybook/'))
|
|
112
|
+
return 'storybook';
|
|
113
|
+
if (/(?:^|\/)(?:__tests__|tests?|e2e)(?:\/|$)|\.(?:test|spec)\.(?:tsx?|jsx?)$|playwright|vitest|jest/.test(lower))
|
|
114
|
+
return 'validation';
|
|
115
|
+
if (/(?:^|\/)(?:routes?|pages?|app)(?:\/|$)|(?:^|\/)router\./.test(lower))
|
|
116
|
+
return 'route';
|
|
117
|
+
if (/(?:^|\/)(?:components?|ui)(?:\/|$)|[A-Z][A-Za-z0-9_-]*\.(?:tsx|jsx|vue|svelte)$/.test(path))
|
|
118
|
+
return 'component';
|
|
119
|
+
if (/(?:tokens?|theme|tailwind|design-system)|\.(?:css|scss)$/.test(lower))
|
|
120
|
+
return 'token';
|
|
121
|
+
if (/(?:openapi|asyncapi|contracts?|schemas?|events?)|\.(?:graphql|proto)$/.test(lower))
|
|
122
|
+
return 'contract';
|
|
123
|
+
if (lower === 'package.json' || lower.startsWith('docs/architecture') || lower.startsWith('docs/arquitetura-software'))
|
|
124
|
+
return 'source_summary';
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
function structuralSummary(kind, content) {
|
|
128
|
+
let identifierCount = 0;
|
|
129
|
+
const patterns = [
|
|
130
|
+
/\bexport\s+(?:default\s+)?(?:async\s+)?(?:function|class|const|let|var|interface|type|enum)\s+([A-Za-z_$][\w$]*)/g,
|
|
131
|
+
/\b(?:GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\b/g,
|
|
132
|
+
/--([a-z][a-z0-9-]{1,64})\s*:/gi,
|
|
133
|
+
];
|
|
134
|
+
for (const pattern of patterns) {
|
|
135
|
+
for (const match of content.matchAll(pattern)) {
|
|
136
|
+
const identifier = (match[1] ?? match[0]).replace(/^--/, '');
|
|
137
|
+
if (/^[A-Za-z_$][\w$-]{0,64}$/.test(identifier))
|
|
138
|
+
identifierCount += 1;
|
|
139
|
+
if (identifierCount >= 12)
|
|
140
|
+
break;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return `${kind}; lines=${content.split(/\r?\n/).length}; structuralIdentifiers=${identifierCount}`;
|
|
144
|
+
}
|
|
145
|
+
function opaqueEvidencePath(kind, relativePath) {
|
|
146
|
+
const extension = relativePath.match(/\.[A-Za-z0-9]+$/)?.[0].toLowerCase() ?? '.json';
|
|
147
|
+
return `evidence/${kind}/${sha256(relativePath).slice(0, 20)}${extension}`;
|
|
148
|
+
}
|
|
149
|
+
function consentFor(options, collectedAt) {
|
|
150
|
+
const consent = options.consent ?? {};
|
|
151
|
+
const redactionPolicy = consent.redactionPolicy && REDACTION_POLICIES.has(consent.redactionPolicy) ? consent.redactionPolicy : undefined;
|
|
152
|
+
const expiresAt = typeof consent.expiresAt === 'string' ? consent.expiresAt : undefined;
|
|
153
|
+
const collectedMs = Date.parse(collectedAt);
|
|
154
|
+
const expiresMs = expiresAt ? Date.parse(expiresAt) : Number.NaN;
|
|
155
|
+
const ttlValid = Number.isFinite(collectedMs) && Number.isFinite(expiresMs) && expiresMs > collectedMs && expiresMs - collectedMs <= 60 * 60 * 1000;
|
|
156
|
+
return {
|
|
157
|
+
richEvidence: consent.richEvidence === true && !!redactionPolicy && ttlValid,
|
|
158
|
+
screenshots: consent.screenshots === true && consent.richEvidence === true && !!redactionPolicy && ttlValid,
|
|
159
|
+
liveEvidence: consent.liveEvidence === true && consent.richEvidence === true && !!redactionPolicy && ttlValid,
|
|
160
|
+
...(redactionPolicy ? { redactionPolicy } : {}),
|
|
161
|
+
...(expiresAt ? { expiresAt } : {}),
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
function collectFile(root, relativePath, kind, budget) {
|
|
165
|
+
const rejection = pathRejection(relativePath);
|
|
166
|
+
if (rejection)
|
|
167
|
+
return { exclusion: excluded(relativePath, rejection) };
|
|
168
|
+
if (isIgnored(relativePath) || PRIVATE_CONTENT.test(relativePath))
|
|
169
|
+
return { exclusion: excluded(relativePath, 'private_evidence_rejected') };
|
|
170
|
+
if (!kind || !ALLOWED_EXTENSIONS.test(relativePath))
|
|
171
|
+
return { exclusion: excluded(relativePath, 'unsupported_file_type') };
|
|
172
|
+
const absolute = resolve(root, relativePath);
|
|
173
|
+
if (!insideRoot(root, absolute))
|
|
174
|
+
return { exclusion: excluded(relativePath, 'traversal_path_rejected') };
|
|
175
|
+
const stat = lstatSync(absolute);
|
|
176
|
+
if (stat.isSymbolicLink())
|
|
177
|
+
return { exclusion: excluded(relativePath, 'symlink_escape_rejected') };
|
|
178
|
+
const real = realpathSync(absolute);
|
|
179
|
+
if (!insideRoot(root, real))
|
|
180
|
+
return { exclusion: excluded(relativePath, 'symlink_escape_rejected') };
|
|
181
|
+
const realStat = statSync(real);
|
|
182
|
+
if (!realStat.isFile())
|
|
183
|
+
return { exclusion: excluded(relativePath, 'unsupported_file_type') };
|
|
184
|
+
if (realStat.size > budget.maxFileBytes)
|
|
185
|
+
return { exclusion: excluded(relativePath, 'oversized_evidence') };
|
|
186
|
+
const content = readFileSync(real);
|
|
187
|
+
if (content.includes(0) || PRIVATE_CONTENT.test(content.toString('utf8')))
|
|
188
|
+
return { exclusion: excluded(relativePath, 'private_evidence_rejected') };
|
|
189
|
+
const normalized = normalizePath(relativePath);
|
|
190
|
+
const contentHash = sha256(content);
|
|
191
|
+
const publicPath = opaqueEvidencePath(kind, normalized);
|
|
192
|
+
return {
|
|
193
|
+
item: {
|
|
194
|
+
id: `${kind}:${sha256(`${normalized}:${contentHash}`).slice(0, 20)}`,
|
|
195
|
+
kind,
|
|
196
|
+
source: { path: publicPath, contentHash, byteLength: realStat.size },
|
|
197
|
+
summary: structuralSummary(kind, content.toString('utf8')).slice(0, budget.maxSummaryChars),
|
|
198
|
+
},
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
function collectRichCandidate(root, candidate, consent, budget) {
|
|
202
|
+
const rejection = pathRejection(candidate.path);
|
|
203
|
+
if (rejection)
|
|
204
|
+
return { exclusion: excluded(candidate.path, rejection) };
|
|
205
|
+
if (!RICH_EXTENSIONS.test(candidate.path))
|
|
206
|
+
return { exclusion: excluded(candidate.path, 'unsupported_file_type') };
|
|
207
|
+
if (!consent.richEvidence || (candidate.kind === 'screenshot' ? !consent.screenshots : !consent.liveEvidence))
|
|
208
|
+
return { exclusion: excluded(candidate.path, 'consent_required') };
|
|
209
|
+
if (!candidate.redactionPolicy || !REDACTION_POLICIES.has(candidate.redactionPolicy) || candidate.redactionPolicy !== consent.redactionPolicy)
|
|
210
|
+
return { exclusion: excluded(candidate.path, 'redaction_policy_required') };
|
|
211
|
+
if (!candidate.expiresAt || candidate.expiresAt !== consent.expiresAt)
|
|
212
|
+
return { exclusion: excluded(candidate.path, 'ttl_invalid') };
|
|
213
|
+
if (isIgnored(candidate.path))
|
|
214
|
+
return { exclusion: excluded(candidate.path, 'private_evidence_rejected') };
|
|
215
|
+
const absolute = resolve(root, candidate.path);
|
|
216
|
+
if (!insideRoot(root, absolute))
|
|
217
|
+
return { exclusion: excluded(candidate.path, 'traversal_path_rejected') };
|
|
218
|
+
const stat = lstatSync(absolute);
|
|
219
|
+
if (stat.isSymbolicLink())
|
|
220
|
+
return { exclusion: excluded(candidate.path, 'symlink_escape_rejected') };
|
|
221
|
+
const real = realpathSync(absolute);
|
|
222
|
+
if (!insideRoot(root, real))
|
|
223
|
+
return { exclusion: excluded(candidate.path, 'symlink_escape_rejected') };
|
|
224
|
+
const realStat = statSync(real);
|
|
225
|
+
if (!realStat.isFile())
|
|
226
|
+
return { exclusion: excluded(candidate.path, 'unsupported_file_type') };
|
|
227
|
+
if (realStat.size > budget.maxFileBytes)
|
|
228
|
+
return { exclusion: excluded(candidate.path, 'oversized_evidence') };
|
|
229
|
+
const content = readFileSync(real);
|
|
230
|
+
const normalized = normalizePath(candidate.path);
|
|
231
|
+
const source = { path: opaqueEvidencePath(candidate.kind, normalized), contentHash: sha256(content), byteLength: realStat.size };
|
|
232
|
+
return {
|
|
233
|
+
item: {
|
|
234
|
+
id: `${candidate.kind}:${sha256(`${normalized}:${source.contentHash}`).slice(0, 20)}`,
|
|
235
|
+
kind: candidate.kind,
|
|
236
|
+
source,
|
|
237
|
+
summary: `${candidate.kind}; metadata-only; bytes=${source.byteLength}`,
|
|
238
|
+
consent: { redactionPolicy: candidate.redactionPolicy, expiresAt: candidate.expiresAt },
|
|
239
|
+
},
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
export function collectProjectEvidence(options) {
|
|
243
|
+
const root = realpathSync(options.projectRoot);
|
|
244
|
+
const collectedAt = new Date(options.collectedAt ?? Date.now()).toISOString();
|
|
245
|
+
const budget = { ...CLIENT_PROJECT_EVIDENCE_BUDGET, ...options.budget };
|
|
246
|
+
const consent = consentFor(options, collectedAt);
|
|
247
|
+
const exclusions = [];
|
|
248
|
+
const explicitCandidates = [];
|
|
249
|
+
for (const candidate of [...(options.candidatePaths ?? [])].sort()) {
|
|
250
|
+
try {
|
|
251
|
+
expandExplicitCandidate(root, candidate, explicitCandidates, exclusions);
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
exclusions.push(excluded(candidate, 'malformed_evidence'));
|
|
255
|
+
}
|
|
256
|
+
if (explicitCandidates.length >= MAX_SCAN_ENTRIES)
|
|
257
|
+
break;
|
|
258
|
+
}
|
|
259
|
+
const fallbackCandidates = [];
|
|
260
|
+
if (!options.candidatePaths || options.includeFallbackInventory === true) {
|
|
261
|
+
inventory(root, root, fallbackCandidates, exclusions, Math.max(0, MAX_SCAN_ENTRIES - explicitCandidates.length));
|
|
262
|
+
}
|
|
263
|
+
const explicitSet = new Set(explicitCandidates.map(normalizePath));
|
|
264
|
+
const candidates = [...new Set([...explicitCandidates, ...fallbackCandidates])].slice(0, MAX_SCAN_ENTRIES);
|
|
265
|
+
const collected = [];
|
|
266
|
+
for (const candidate of candidates) {
|
|
267
|
+
let result;
|
|
268
|
+
try {
|
|
269
|
+
result = collectFile(root, candidate, kindFor(normalizePath(candidate)), budget);
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
result = { exclusion: excluded(candidate, 'malformed_evidence') };
|
|
273
|
+
}
|
|
274
|
+
if (result.exclusion)
|
|
275
|
+
exclusions.push(result.exclusion);
|
|
276
|
+
if (result.item)
|
|
277
|
+
collected.push({ candidate, explicit: explicitSet.has(normalizePath(candidate)), item: result.item });
|
|
278
|
+
}
|
|
279
|
+
const byKind = new Map();
|
|
280
|
+
for (const entry of collected)
|
|
281
|
+
byKind.set(entry.item.kind, [...(byKind.get(entry.item.kind) ?? []), entry]);
|
|
282
|
+
const priority = (left, right) => Number(right.explicit) - Number(left.explicit) || left.candidate.localeCompare(right.candidate);
|
|
283
|
+
for (const entries of byKind.values())
|
|
284
|
+
entries.sort(priority);
|
|
285
|
+
const reserved = [...byKind.keys()].sort().flatMap((kind) => byKind.get(kind)?.slice(0, 1) ?? []);
|
|
286
|
+
const reservedIds = new Set(reserved.map((entry) => entry.item.id));
|
|
287
|
+
const fill = collected.filter((entry) => !reservedIds.has(entry.item.id)).sort(priority);
|
|
288
|
+
const evidence = [];
|
|
289
|
+
let acceptedBytes = 0;
|
|
290
|
+
for (const entry of [...reserved, ...fill]) {
|
|
291
|
+
if (evidence.length >= budget.maxItems || acceptedBytes + entry.item.source.byteLength > budget.maxTotalBytes) {
|
|
292
|
+
exclusions.push(excluded(entry.candidate, 'budget_exceeded'));
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
evidence.push(entry.item);
|
|
296
|
+
acceptedBytes += entry.item.source.byteLength;
|
|
297
|
+
}
|
|
298
|
+
for (const candidate of options.richCandidates ?? []) {
|
|
299
|
+
let result;
|
|
300
|
+
try {
|
|
301
|
+
result = collectRichCandidate(root, candidate, consent, budget);
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
result = { exclusion: excluded(candidate.path, 'malformed_evidence') };
|
|
305
|
+
}
|
|
306
|
+
if (result.exclusion)
|
|
307
|
+
exclusions.push(result.exclusion);
|
|
308
|
+
if (!result.item)
|
|
309
|
+
continue;
|
|
310
|
+
if (evidence.length >= budget.maxItems || acceptedBytes + result.item.source.byteLength > budget.maxTotalBytes) {
|
|
311
|
+
exclusions.push(excluded(candidate.path, 'budget_exceeded'));
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
evidence.push(result.item);
|
|
315
|
+
acceptedBytes += result.item.source.byteLength;
|
|
316
|
+
}
|
|
317
|
+
evidence.sort((left, right) => left.kind.localeCompare(right.kind) || left.source.path.localeCompare(right.source.path));
|
|
318
|
+
const evidenceHash = sha256(stableJson(evidence));
|
|
319
|
+
let envelope = {
|
|
320
|
+
schemaVersion: 1,
|
|
321
|
+
envelopeId: `evidence-${evidenceHash.slice(0, 24)}`,
|
|
322
|
+
evidenceHash,
|
|
323
|
+
collectedAt,
|
|
324
|
+
consent,
|
|
325
|
+
budget: { ...budget, acceptedItems: evidence.length, acceptedBytes },
|
|
326
|
+
evidence,
|
|
327
|
+
exclusions: exclusions.slice(0, budget.maxExclusions),
|
|
328
|
+
};
|
|
329
|
+
while (Buffer.byteLength(JSON.stringify(envelope), 'utf8') > budget.maxEnvelopeBytes && envelope.evidence.length > 0) {
|
|
330
|
+
const removed = envelope.evidence.at(-1);
|
|
331
|
+
const nextEvidence = envelope.evidence.slice(0, -1);
|
|
332
|
+
const nextHash = sha256(stableJson(nextEvidence));
|
|
333
|
+
envelope = {
|
|
334
|
+
...envelope,
|
|
335
|
+
envelopeId: `evidence-${nextHash.slice(0, 24)}`,
|
|
336
|
+
evidenceHash: nextHash,
|
|
337
|
+
budget: {
|
|
338
|
+
...envelope.budget,
|
|
339
|
+
acceptedItems: nextEvidence.length,
|
|
340
|
+
acceptedBytes: nextEvidence.reduce((total, item) => total + item.source.byteLength, 0),
|
|
341
|
+
},
|
|
342
|
+
evidence: nextEvidence,
|
|
343
|
+
exclusions: [...envelope.exclusions, excluded(removed.id, 'budget_exceeded')].slice(0, budget.maxExclusions),
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
return envelope;
|
|
347
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export { CLIENT_PROJECT_EVIDENCE_BUDGET, collectProjectEvidence } from './collector.js';
|
|
@@ -1 +1,152 @@
|
|
|
1
|
-
import{randomUUID
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
3
|
+
import { basename, dirname, join } from 'node:path';
|
|
4
|
+
const ATOMIC_TOKEN = /^\d+\.[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}\.(tmp|swap)$/i;
|
|
5
|
+
/**
|
|
6
|
+
* Recover a fully-fsynced artifact left by a process crash. A swap is the
|
|
7
|
+
* conservative authority because it restores the last committed destination;
|
|
8
|
+
* without a swap, one unambiguous temp can be promoted for first creation.
|
|
9
|
+
*/
|
|
10
|
+
export function recoverAtomicReplaceUtf8(path) {
|
|
11
|
+
const directory = dirname(path);
|
|
12
|
+
if (!existsSync(directory))
|
|
13
|
+
return 'none';
|
|
14
|
+
const prefix = `${basename(path)}.`;
|
|
15
|
+
const artifacts = readdirSync(directory)
|
|
16
|
+
.filter((entry) => entry.startsWith(prefix) && ATOMIC_TOKEN.test(entry.slice(prefix.length)))
|
|
17
|
+
.map((entry) => ({
|
|
18
|
+
entry,
|
|
19
|
+
path: join(directory, entry),
|
|
20
|
+
kind: entry.endsWith('.swap') ? 'swap' : 'tmp',
|
|
21
|
+
}));
|
|
22
|
+
if (existsSync(path)) {
|
|
23
|
+
if (!lstatSync(path).isFile())
|
|
24
|
+
throw new Error('ATOMIC_REPLACE_RECOVERY_UNSAFE');
|
|
25
|
+
for (const artifact of artifacts) {
|
|
26
|
+
if (!lstatSync(artifact.path).isFile())
|
|
27
|
+
throw new Error('ATOMIC_REPLACE_RECOVERY_UNSAFE');
|
|
28
|
+
}
|
|
29
|
+
for (const artifact of artifacts)
|
|
30
|
+
unlinkSync(artifact.path);
|
|
31
|
+
if (artifacts.length > 0)
|
|
32
|
+
fsyncDirectoryBestEffort(directory);
|
|
33
|
+
return 'none';
|
|
34
|
+
}
|
|
35
|
+
const swaps = artifacts.filter((artifact) => artifact.kind === 'swap');
|
|
36
|
+
const temps = artifacts.filter((artifact) => artifact.kind === 'tmp');
|
|
37
|
+
if (swaps.length > 1 || (swaps.length === 0 && temps.length > 1)) {
|
|
38
|
+
throw new Error('ATOMIC_REPLACE_RECOVERY_AMBIGUOUS');
|
|
39
|
+
}
|
|
40
|
+
const selected = swaps[0] ?? temps[0];
|
|
41
|
+
if (!selected)
|
|
42
|
+
return 'none';
|
|
43
|
+
if (!lstatSync(selected.path).isFile())
|
|
44
|
+
throw new Error('ATOMIC_REPLACE_RECOVERY_UNSAFE');
|
|
45
|
+
renameSync(selected.path, path);
|
|
46
|
+
for (const artifact of artifacts) {
|
|
47
|
+
if (artifact.path === selected.path || !existsSync(artifact.path))
|
|
48
|
+
continue;
|
|
49
|
+
try {
|
|
50
|
+
unlinkSync(artifact.path);
|
|
51
|
+
}
|
|
52
|
+
catch { /* recovered destination is authoritative */ }
|
|
53
|
+
}
|
|
54
|
+
fsyncDirectoryBestEffort(directory);
|
|
55
|
+
return selected.kind === 'swap' ? 'restored-swap' : 'promoted-temp';
|
|
56
|
+
}
|
|
57
|
+
/** Best-effort directory durability; Windows can reject directory handles. */
|
|
58
|
+
export function fsyncDirectoryBestEffort(path) {
|
|
59
|
+
let fd;
|
|
60
|
+
try {
|
|
61
|
+
fd = openSync(path, 'r');
|
|
62
|
+
fsyncSync(fd);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
// The temp file itself is always fsynced before replacement. On hosts that
|
|
66
|
+
// cannot fsync directories this is the strongest portable boundary.
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
if (fd !== undefined)
|
|
70
|
+
closeSync(fd);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** Create a new UTF-8 file and make its contents durable before returning. */
|
|
74
|
+
export function durableCreateUtf8(path, contents) {
|
|
75
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
76
|
+
let fd;
|
|
77
|
+
try {
|
|
78
|
+
fd = openSync(path, 'wx', 0o600);
|
|
79
|
+
writeFileSync(fd, contents, 'utf8');
|
|
80
|
+
fsyncSync(fd);
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (fd !== undefined) {
|
|
84
|
+
try {
|
|
85
|
+
closeSync(fd);
|
|
86
|
+
}
|
|
87
|
+
catch { /* best effort before cleanup */ }
|
|
88
|
+
fd = undefined;
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
if (existsSync(path))
|
|
92
|
+
unlinkSync(path);
|
|
93
|
+
}
|
|
94
|
+
catch { /* best effort */ }
|
|
95
|
+
fsyncDirectoryBestEffort(dirname(path));
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
if (fd !== undefined)
|
|
100
|
+
closeSync(fd);
|
|
101
|
+
}
|
|
102
|
+
fsyncDirectoryBestEffort(dirname(path));
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Replace one UTF-8 state file without truncating the live destination.
|
|
106
|
+
* The fallback swap exists for Windows rename semantics and restores the
|
|
107
|
+
* original if installing the new file fails.
|
|
108
|
+
*/
|
|
109
|
+
export function atomicReplaceUtf8(path, contents) {
|
|
110
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
111
|
+
const token = `${process.pid}.${randomUUID()}`;
|
|
112
|
+
const temp = `${path}.${token}.tmp`;
|
|
113
|
+
const swap = `${path}.${token}.swap`;
|
|
114
|
+
writeFileSync(temp, contents, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
115
|
+
const fd = openSync(temp, 'r');
|
|
116
|
+
try {
|
|
117
|
+
fsyncSync(fd);
|
|
118
|
+
}
|
|
119
|
+
finally {
|
|
120
|
+
closeSync(fd);
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
renameSync(temp, path);
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
let movedOriginal = false;
|
|
127
|
+
try {
|
|
128
|
+
if (existsSync(path)) {
|
|
129
|
+
renameSync(path, swap);
|
|
130
|
+
movedOriginal = true;
|
|
131
|
+
}
|
|
132
|
+
renameSync(temp, path);
|
|
133
|
+
}
|
|
134
|
+
catch (fallbackError) {
|
|
135
|
+
if (movedOriginal && !existsSync(path) && existsSync(swap))
|
|
136
|
+
renameSync(swap, path);
|
|
137
|
+
try {
|
|
138
|
+
if (existsSync(temp))
|
|
139
|
+
unlinkSync(temp);
|
|
140
|
+
}
|
|
141
|
+
catch { /* best effort */ }
|
|
142
|
+
throw fallbackError;
|
|
143
|
+
}
|
|
144
|
+
if (movedOriginal) {
|
|
145
|
+
try {
|
|
146
|
+
unlinkSync(swap);
|
|
147
|
+
}
|
|
148
|
+
catch { /* stale swap is safer than an uncertain replace */ }
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
fsyncDirectoryBestEffort(dirname(path));
|
|
152
|
+
}
|