@planu/cli 6.0.0 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/.planu-build.json +1 -1
  3. package/dist/cli/commands/job.js +7 -1
  4. package/dist/cli/router.js +24 -5
  5. package/dist/config/official-sdd-tools.d.ts +0 -1
  6. package/dist/config/official-sdd-tools.js +0 -3
  7. package/dist/core/spec-validator.js +1 -1
  8. package/dist/engine/coach/i18n.d.ts +1 -1
  9. package/dist/engine/coach/i18n.js +2 -2
  10. package/dist/engine/convention-scanner/codebase-scanner.js +140 -8
  11. package/dist/engine/conventions-ttl.d.ts +0 -2
  12. package/dist/engine/conventions-ttl.js +1 -1
  13. package/dist/engine/evidence-gates/artifact-reader.d.ts +0 -2
  14. package/dist/engine/evidence-gates/artifact-reader.js +0 -2
  15. package/dist/engine/execution/package-handoff-job-executor.d.ts +1 -1
  16. package/dist/engine/execution/package-handoff-job-executor.js +42 -13
  17. package/dist/engine/execution/startup-recovery.d.ts +3 -0
  18. package/dist/engine/execution/startup-recovery.js +15 -0
  19. package/dist/engine/execution/validate-job-executor.d.ts +1 -1
  20. package/dist/engine/execution/validate-job-executor.js +23 -3
  21. package/dist/engine/handoff-packager.d.ts +2 -0
  22. package/dist/engine/handoff-packager.js +25 -9
  23. package/dist/engine/network-policy.js +31 -0
  24. package/dist/engine/test-selection/policy.js +1 -1
  25. package/dist/engine/validation-evidence-ledger.js +8 -37
  26. package/dist/engine/validation-impact-planner.d.ts +1 -3
  27. package/dist/engine/validation-impact-planner.js +2 -18
  28. package/dist/engine/validator/analyzer.js +0 -1
  29. package/dist/engine/validator/reliability-gate.js +6 -1
  30. package/dist/index.js +3 -11
  31. package/dist/security/adapters/local-file.js +8 -1
  32. package/dist/security/secret-provider.js +0 -2
  33. package/dist/storage/migrations/sdd-core-v6.js +101 -23
  34. package/dist/storage/project-identity.js +18 -2
  35. package/dist/tools/check-readiness.js +45 -35
  36. package/dist/tools/create-spec.js +14 -16
  37. package/dist/tools/init-project/agents-md-writer.js +0 -3
  38. package/dist/tools/package-handoff.js +19 -16
  39. package/dist/tools/update-status/approval-gates.d.ts +1 -1
  40. package/dist/tools/update-status/approval-gates.js +28 -5
  41. package/dist/tools/update-status/evidence-payload.d.ts +0 -2
  42. package/dist/tools/update-status/index.js +18 -8
  43. package/dist/tools/update-status/transition-guard.d.ts +1 -1
  44. package/dist/tools/update-status/transition-guard.js +18 -2
  45. package/dist/tools/validate.js +29 -7
  46. package/dist/types/common/learning.d.ts +0 -17
  47. package/dist/types/durable-job.d.ts +15 -1
  48. package/dist/types/index.d.ts +0 -3
  49. package/dist/types/index.js +0 -3
  50. package/dist/types/living-spec/annotations.d.ts +0 -30
  51. package/dist/types/living-spec/annotations.js +14 -0
  52. package/dist/types/living-spec.d.ts +0 -1
  53. package/dist/types/living-spec.js +0 -1
  54. package/dist/types/project/core.d.ts +0 -2
  55. package/dist/types/project/planu-config.d.ts +0 -1
  56. package/dist/types/readiness.d.ts +2 -0
  57. package/dist/types/security.d.ts +1 -1
  58. package/dist/types/spec-quality.d.ts +0 -20
  59. package/dist/types/timing.d.ts +0 -6
  60. package/dist/types/validation-evidence.d.ts +2 -2
  61. package/dist/types/validation.d.ts +2 -0
  62. package/package.json +4 -4
  63. package/scripts/check-reliability-policies.mjs +504 -0
  64. package/dist/engine/timing/structured-log.d.ts +0 -10
  65. package/dist/engine/timing/structured-log.js +0 -36
  66. package/dist/types/analysis-detection.d.ts +0 -14
  67. package/dist/types/analysis-detection.js +0 -5
  68. package/dist/types/lessons.d.ts +0 -28
  69. package/dist/types/lessons.js +0 -3
  70. package/dist/types/living-spec/dashboard-and-sync.d.ts +0 -82
  71. package/dist/types/living-spec/dashboard-and-sync.js +0 -3
  72. package/dist/types/vector-store.d.ts +0 -46
  73. package/dist/types/vector-store.js +0 -21
  74. package/planu-plugin.json +0 -35
@@ -5,10 +5,15 @@ let installed = false;
5
5
  const require = createRequire(import.meta.url);
6
6
  const httpModule = require('node:http');
7
7
  const httpsModule = require('node:https');
8
+ const netModule = require('node:net');
9
+ const tlsModule = require('node:tls');
8
10
  const originalHttpRequest = httpModule.request;
9
11
  const originalHttpGet = httpModule.get;
10
12
  const originalHttpsRequest = httpsModule.request;
11
13
  const originalHttpsGet = httpsModule.get;
14
+ const originalNetConnect = netModule.connect;
15
+ const originalNetCreateConnection = netModule.createConnection;
16
+ const originalTlsConnect = tlsModule.connect;
12
17
  class NetworkBlockedError extends Error {
13
18
  destination;
14
19
  code = 'PLANU_NETWORK_BLOCKED';
@@ -36,6 +41,26 @@ function guardedRequest(protocol) {
36
41
  throw new NetworkBlockedError(requestDestination(protocol, args));
37
42
  };
38
43
  }
44
+ function socketDestination(protocol, args) {
45
+ const first = args[0];
46
+ if (typeof first === 'string') {
47
+ return `${protocol}//${first}`;
48
+ }
49
+ if (typeof first === 'number') {
50
+ const host = typeof args[1] === 'string' ? args[1] : 'localhost';
51
+ return `${protocol}//${host}:${String(first)}`;
52
+ }
53
+ const options = (first ?? {});
54
+ if (options.path) {
55
+ return `${protocol}//${options.path}`;
56
+ }
57
+ return `${protocol}//${options.host ?? 'localhost'}:${String(options.port ?? '')}`;
58
+ }
59
+ function guardedSocket(protocol) {
60
+ return (...args) => {
61
+ throw new NetworkBlockedError(socketDestination(protocol, args));
62
+ };
63
+ }
39
64
  /** Install once; all network clients fail before touching a transport. */
40
65
  export function installNetworkPolicy() {
41
66
  if (installed) {
@@ -50,6 +75,9 @@ export function installNetworkPolicy() {
50
75
  httpModule.get = guardedRequest('http:');
51
76
  httpsModule.request = guardedRequest('https:');
52
77
  httpsModule.get = guardedRequest('https:');
78
+ netModule.connect = guardedSocket('tcp:');
79
+ netModule.createConnection = guardedSocket('tcp:');
80
+ tlsModule.connect = guardedSocket('tls:');
53
81
  syncBuiltinESMExports();
54
82
  installed = true;
55
83
  }
@@ -59,6 +87,9 @@ export function restoreNetworkPolicyForTests() {
59
87
  httpModule.get = originalHttpGet;
60
88
  httpsModule.request = originalHttpsRequest;
61
89
  httpsModule.get = originalHttpsGet;
90
+ netModule.connect = originalNetConnect;
91
+ netModule.createConnection = originalNetCreateConnection;
92
+ tlsModule.connect = originalTlsConnect;
62
93
  syncBuiltinESMExports();
63
94
  installed = false;
64
95
  }
@@ -33,7 +33,7 @@ const ROOT_TOOLCHAIN_CONFIGS = new Set([
33
33
  'vitest.config.ts',
34
34
  'tsconfig.json',
35
35
  ]);
36
- const NONEXECUTABLE_ROOTS = ['planu/', 'docs/', '.claude/', 'website/', 'memory/'];
36
+ const NONEXECUTABLE_ROOTS = ['planu/', 'docs/', '.claude/', 'memory/'];
37
37
  export function withIntegrationPolicy(base, policy) {
38
38
  const { PLANU_EXCLUDE_INTEGRATION_TESTS: _exclude, PLANU_INTEGRATION_TESTS_ONLY: _only, ...rest } = base;
39
39
  return { ...rest, ...INTEGRATION_POLICY_ENV[policy] };
@@ -15,11 +15,9 @@ const LOCK_PATHS = {
15
15
  contract: PACKAGE_LOCKS,
16
16
  coverage: PACKAGE_LOCKS,
17
17
  migration: PACKAGE_LOCKS,
18
- 'fault-injection': [...PACKAGE_LOCKS, 'Cargo.lock'],
19
- security: [...PACKAGE_LOCKS, 'Cargo.lock'],
20
- native: [...PACKAGE_LOCKS, 'Cargo.lock'],
21
- website: PACKAGE_LOCKS,
22
- reproducibility: [...PACKAGE_LOCKS, 'Cargo.lock'],
18
+ 'fault-injection': PACKAGE_LOCKS,
19
+ security: PACKAGE_LOCKS,
20
+ reproducibility: PACKAGE_LOCKS,
23
21
  };
24
22
  const CONFIG_PATHS = {
25
23
  typecheck: ['package.json', 'pnpm-workspace.yaml', 'tsconfig.json', 'tsconfig.build.json'],
@@ -29,17 +27,9 @@ const CONFIG_PATHS = {
29
27
  contract: ['package.json', 'vitest.config.ts', 'vitest.config.mts', 'vitest.config.js'],
30
28
  coverage: ['package.json', 'vitest.config.ts', 'vitest.config.mts', 'vitest.config.js'],
31
29
  migration: ['package.json', 'vitest.config.ts', 'vitest.config.mts', 'vitest.config.js'],
32
- 'fault-injection': [
33
- 'package.json',
34
- 'vitest.config.ts',
35
- 'vitest.config.mts',
36
- 'vitest.config.js',
37
- 'Cargo.toml',
38
- ],
39
- security: ['package.json', 'pnpm-workspace.yaml', 'Cargo.toml'],
40
- native: ['package.json', 'pnpm-workspace.yaml', 'Cargo.toml'],
41
- website: ['package.json', 'website/package.json'],
42
- reproducibility: ['package.json', 'pnpm-workspace.yaml', 'tsconfig.build.json', 'Cargo.toml'],
30
+ 'fault-injection': ['package.json', 'vitest.config.ts', 'vitest.config.mts', 'vitest.config.js'],
31
+ security: ['package.json', 'pnpm-workspace.yaml'],
32
+ reproducibility: ['package.json', 'pnpm-workspace.yaml', 'tsconfig.build.json'],
43
33
  };
44
34
  const CAPABILITY_PATHS = {
45
35
  typecheck: [
@@ -72,33 +62,14 @@ const CAPABILITY_PATHS = {
72
62
  ],
73
63
  'fault-injection': [
74
64
  'src/engine/execution',
75
- 'src/engine/auto-updater',
76
65
  'src/storage/runtime-db.ts',
77
66
  'tests/engine',
78
67
  'tests/integration',
79
68
  'package.json',
80
69
  'pnpm-lock.yaml',
81
- 'rust',
82
- ],
83
- security: [
84
- 'package.json',
85
- 'pnpm-lock.yaml',
86
- 'pnpm-workspace.yaml',
87
- 'Cargo.toml',
88
- 'Cargo.lock',
89
- 'npm',
90
- ],
91
- native: ['rust', 'npm', 'Cargo.toml', 'Cargo.lock', 'package.json', 'pnpm-lock.yaml'],
92
- website: ['website', 'package.json', 'pnpm-lock.yaml'],
93
- reproducibility: [
94
- 'src',
95
- 'rust',
96
- 'npm',
97
- 'scripts',
98
- 'package.json',
99
- 'pnpm-lock.yaml',
100
- 'tsconfig.build.json',
101
70
  ],
71
+ security: ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml'],
72
+ reproducibility: ['src', 'scripts', 'package.json', 'pnpm-lock.yaml', 'tsconfig.build.json'],
102
73
  };
103
74
  export function normalizeValidationCommand(command) {
104
75
  return command.trim().split(/\s+/).join(' ');
@@ -8,9 +8,7 @@ export declare const VALIDATION_COMMANDS: {
8
8
  readonly coverage: 'pnpm test:coverage';
9
9
  readonly migration: 'pnpm test:migrations';
10
10
  readonly 'fault-injection': 'pnpm test:fault-injection';
11
- readonly security: 'pnpm check:deps:fresh';
12
- readonly native: 'pnpm native:project-graph:e2e';
13
- readonly website: 'pnpm --dir website build';
11
+ readonly security: 'pnpm audit --audit-level=high';
14
12
  };
15
13
  export declare function planValidationImpact(paths: readonly string[]): ValidationImpactPlan;
16
14
  //# sourceMappingURL=validation-impact-planner.d.ts.map
@@ -8,15 +8,12 @@ export const VALIDATION_COMMANDS = {
8
8
  coverage: 'pnpm test:coverage',
9
9
  migration: 'pnpm test:migrations',
10
10
  'fault-injection': 'pnpm test:fault-injection',
11
- security: 'pnpm check:deps:fresh',
12
- native: 'pnpm native:project-graph:e2e',
13
- website: 'pnpm --dir website build',
11
+ security: 'pnpm audit --audit-level=high',
14
12
  };
15
13
  const LIFECYCLE_RE = /^(?:planu\/|docs\/|README(?:\.|$)|CHANGELOG\.md$|[^/]+\.md$)/;
16
14
  const SOURCE_RE = /^(?:src\/|tests\/)/;
17
- const CORE_RE = /^(?:src\/|rust\/planu-core\/|tests\/(?:contracts|engine|integration|storage|tools)\/)/;
15
+ const CORE_RE = /^(?:src\/|tests\/(?:contracts|engine|integration|storage|tools)\/)/;
18
16
  const DEPENDENCY_RE = /^(?:package\.json|pnpm-lock\.yaml|pnpm-workspace\.yaml|npm\/[^/]+\/package\.json)/;
19
- const NATIVE_RE = /^(?:rust\/|Cargo\.(?:toml|lock)$|npm\/(?:core-|(?:darwin|linux|win32)-))/;
20
17
  const SHARED_RE = /^(?:\.github\/|\.husky\/|scripts\/|tsconfig(?:\.[^/]+)?\.json$|eslint\.config\.[^/]+$|vitest\.config\.[^/]+$)/;
21
18
  export function planValidationImpact(paths) {
22
19
  const changedPaths = [...new Set(paths.map(normalizePath).filter(Boolean))].sort();
@@ -41,18 +38,9 @@ export function planValidationImpact(paths) {
41
38
  gates.add('lint');
42
39
  gates.add('test-related');
43
40
  }
44
- else if (NATIVE_RE.test(path)) {
45
- kind = 'native';
46
- gates.add('native');
47
- gates.add('test-full');
48
- }
49
41
  else if (DEPENDENCY_RE.test(path)) {
50
42
  return fullPlan('Dependency or lockfile change selects every reliability gate.', changedPaths);
51
43
  }
52
- else if (path.startsWith('website/')) {
53
- kind = kind === 'none' ? 'website' : kind;
54
- gates.add('website');
55
- }
56
44
  else if (!LIFECYCLE_RE.test(path)) {
57
45
  return fullPlan(`Unknown path selects fail-safe full validation: ${path}`, changedPaths);
58
46
  }
@@ -69,11 +57,7 @@ function fullPlan(reason, changedPaths) {
69
57
  'security',
70
58
  'migration',
71
59
  'fault-injection',
72
- 'native',
73
60
  ];
74
- if (changedPaths.some((path) => path.startsWith('website/'))) {
75
- gates.push('website');
76
- }
77
61
  return plan('full', gates, true, reason, changedPaths);
78
62
  }
79
63
  function plan(kind, gates, heavy, reason, changedPaths) {
@@ -128,7 +128,6 @@ export async function scanCodeForSpec(spec, projectPath) {
128
128
  '.git/**',
129
129
  'docs-site/**',
130
130
  'planu/specs/**',
131
- 'website/**',
132
131
  'coverage/**',
133
132
  ],
134
133
  maxDepth: 6,
@@ -1,4 +1,5 @@
1
1
  import { execFileSync } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
2
3
  import { relative, resolve } from 'node:path';
3
4
  const PROTECTED_DIRECTORIES = [
4
5
  'src/storage',
@@ -9,6 +10,7 @@ const PROTECTED_DIRECTORIES = [
9
10
  'src/engine/safety',
10
11
  'src/engine/core-bridge.ts',
11
12
  ];
13
+ const CHECKER_PATH = fileURLToPath(new URL('../../../scripts/check-reliability-policies.mjs', import.meta.url));
12
14
  function normalizeToProjectRelative(projectPath, file) {
13
15
  return relative(projectPath, resolve(projectPath, file));
14
16
  }
@@ -41,7 +43,10 @@ export function runReliabilityGate(projectPath, specFiles) {
41
43
  }
42
44
  let stdout;
43
45
  try {
44
- stdout = execFileSync(process.execPath, ['scripts/check-reliability-policies.mjs', '--root', projectPath, '--json'], { cwd: process.cwd(), encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
46
+ stdout = execFileSync(process.execPath, [CHECKER_PATH, '--root', projectPath, '--json'], {
47
+ encoding: 'utf-8',
48
+ stdio: ['ignore', 'pipe', 'pipe'],
49
+ });
45
50
  }
46
51
  catch (error) {
47
52
  const stdoutFromError = error.stdout;
package/dist/index.js CHANGED
@@ -54,19 +54,12 @@ function createMcpServer() {
54
54
  }
55
55
  // Primary server instance — created immediately at module load with minimal deps.
56
56
  const server = createMcpServer();
57
- function scheduleStartupStateRecovery() {
58
- void import('./engine/execution/validate-job-executor.js').then(({ recoverValidateJobsAtStartup }) => {
59
- recoverValidateJobsAtStartup();
60
- });
61
- void import('./engine/execution/package-handoff-job-executor.js').then(({ recoverPackageHandoffJobsAtStartup }) => {
62
- recoverPackageHandoffJobsAtStartup();
63
- });
64
- }
65
57
  // Loads post-handshake modules after the MCP handshake has completed.
66
58
  // Separated from main() to keep main() within the 80-line function budget.
67
59
  async function setupPostHandshake(handshakeGate) {
68
60
  await handshakeGate;
69
- scheduleStartupStateRecovery();
61
+ const { recoverDurableJobsAtStartup } = await import('./engine/execution/startup-recovery.js');
62
+ await recoverDurableJobsAtStartup();
70
63
  }
71
64
  // Start server
72
65
  async function main() {
@@ -103,8 +96,7 @@ async function main() {
103
96
  await new Promise((res) => {
104
97
  setImmediate(res);
105
98
  });
106
- // Fire-and-forget: setupPostHandshake awaits the gate before optional startup work.
107
- void setupPostHandshake(handshakeGate);
99
+ await setupPostHandshake(handshakeGate);
108
100
  }
109
101
  process.on('uncaughtException', (error) => {
110
102
  /* v8 ignore next 1 */
@@ -34,7 +34,14 @@ export class LocalFileSecretAdapter {
34
34
  await chmod(target, 0o600);
35
35
  }
36
36
  catch (error) {
37
- await unlink(temporary).catch(() => undefined);
37
+ try {
38
+ await unlink(temporary);
39
+ }
40
+ catch (cleanupError) {
41
+ if (cleanupError.code !== 'ENOENT') {
42
+ throw cleanupError;
43
+ }
44
+ }
38
45
  throw error;
39
46
  }
40
47
  }
@@ -6,8 +6,6 @@ const SECRET_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/u;
6
6
  const PROVIDERS = new Set([
7
7
  'local-file',
8
8
  'macos-keychain',
9
- 'linux-secret-service',
10
- 'windows-credential-manager',
11
9
  'environment',
12
10
  ]);
13
11
  const PURPOSES = new Set(['validation-signing']);
@@ -61,6 +61,7 @@ import { DatabaseSync } from 'node:sqlite';
61
61
  import { RuntimeDatabase } from '../runtime-db.js';
62
62
  import { createStorageCatalog } from '../storage-catalog.js';
63
63
  import { resolveSddCoreV6StorageLayout } from '../storage-layout.js';
64
+ import { reportClassifiedDegradation } from '../../errors/classified-degradation.js';
64
65
  const execFileAsync = promisify(execFile);
65
66
  const MIGRATION_VERSION = 6;
66
67
  const RETIRED_REASON = 'retired-by-sdd-core-v6';
@@ -74,6 +75,7 @@ const RETIRED_ACTIONS = new Set([
74
75
  'autopush',
75
76
  'git-autostage',
76
77
  ]);
78
+ const MIGRATION_LOCK_STALE_MS = 5 * 60_000;
77
79
  export class SddCoreV6MigrationError extends Error {
78
80
  code;
79
81
  constructor(code, message, options) {
@@ -402,7 +404,7 @@ async function publishDatabase(layout) {
402
404
  __disposeResources(env_2);
403
405
  }
404
406
  }
405
- if ((await readFile(layout.legacyRuntimeDatabase, 'utf8').catch(() => '')).startsWith(TOMBSTONE)) {
407
+ if ((await readTextIfPresent(layout.legacyRuntimeDatabase))?.startsWith(TOMBSTONE) === true) {
406
408
  if (!(await exists(layout.runtimeDatabase))) {
407
409
  throw new SddCoreV6MigrationError('MIGRATION_INCOMPLETE', 'tombstone exists without v6 database');
408
410
  }
@@ -478,7 +480,7 @@ async function quarantineLegacyBundle(layout) {
478
480
  continue;
479
481
  }
480
482
  if (path === layout.runtimeDatabaseTombstone &&
481
- (await readFile(path, 'utf8').catch(() => '')).startsWith(TOMBSTONE)) {
483
+ (await readTextIfPresent(path))?.startsWith(TOMBSTONE) === true) {
482
484
  continue;
483
485
  }
484
486
  const target = join(layout.sddCoreV6Quarantine, basename(path));
@@ -648,55 +650,131 @@ async function verifyCompleted(layout, marker) {
648
650
  throw new SddCoreV6MigrationError('MIGRATION_INCOMPLETE', 'legacy tombstone is writable');
649
651
  }
650
652
  }
653
+ async function readTextIfPresent(path) {
654
+ try {
655
+ return await readFile(path, 'utf8');
656
+ }
657
+ catch (error) {
658
+ if (error.code === 'ENOENT') {
659
+ return null;
660
+ }
661
+ throw error;
662
+ }
663
+ }
651
664
  async function removeStaleMigrationLock(path) {
652
665
  let parsed;
666
+ let original;
653
667
  try {
654
- parsed = JSON.parse(await readFile(path, 'utf8'));
668
+ original = await readFile(path, 'utf8');
669
+ parsed = JSON.parse(original);
655
670
  }
656
- catch {
671
+ catch (error) {
672
+ reportClassifiedDegradation('MIGRATION_LOCK_PARSE_FAILURE', error);
657
673
  return false;
658
674
  }
659
- if (!isObject(parsed) || parsed.hostname !== hostname() || !Number.isSafeInteger(parsed.pid)) {
675
+ if (!isObject(parsed) ||
676
+ typeof parsed.hostname !== 'string' ||
677
+ !Number.isSafeInteger(parsed.pid) ||
678
+ typeof parsed.createdAt !== 'string') {
660
679
  return false;
661
680
  }
662
- try {
663
- process.kill(parsed.pid, 0);
681
+ const createdAt = Date.parse(parsed.createdAt);
682
+ if (!Number.isFinite(createdAt)) {
664
683
  return false;
665
684
  }
666
- catch (error) {
667
- if (error.code !== 'ESRCH') {
685
+ if (parsed.hostname === hostname()) {
686
+ try {
687
+ process.kill(parsed.pid, 0);
668
688
  return false;
669
689
  }
670
- await rm(path, { force: true });
671
- return true;
690
+ catch (error) {
691
+ if (error.code !== 'ESRCH') {
692
+ return false;
693
+ }
694
+ }
695
+ }
696
+ else if (Date.now() - createdAt <= MIGRATION_LOCK_STALE_MS) {
697
+ return false;
698
+ }
699
+ if ((await readTextIfPresent(path)) !== original) {
700
+ return false;
701
+ }
702
+ await rm(path, { force: true });
703
+ return true;
704
+ }
705
+ async function withMigrationLockGuard(path, action) {
706
+ const guardPath = `${path}.guard.sqlite`;
707
+ let guard;
708
+ try {
709
+ guard = new DatabaseSync(guardPath);
710
+ guard.exec('PRAGMA busy_timeout = 0; PRAGMA journal_mode = DELETE;');
711
+ guard.exec('CREATE TABLE IF NOT EXISTS migration_guard (singleton INTEGER PRIMARY KEY CHECK (singleton = 1))');
712
+ guard.exec('BEGIN EXCLUSIVE');
713
+ }
714
+ catch (error) {
715
+ guard?.close();
716
+ throw new SddCoreV6MigrationError('MIGRATION_BUSY', 'migration lock is being reconciled', {
717
+ cause: error,
718
+ });
719
+ }
720
+ try {
721
+ return await action();
722
+ }
723
+ finally {
724
+ guard.exec('ROLLBACK');
725
+ guard.close();
672
726
  }
673
727
  }
674
728
  async function acquireMigrationLock(layout) {
675
729
  const path = `${layout.sddCoreV6Journal}.lock`;
676
730
  await mkdir(dirname(path), { recursive: true, mode: 0o700 });
677
- for (let attempt = 0; attempt < 2; attempt += 1) {
678
- try {
679
- await writeFile(path, JSON.stringify({ pid: process.pid, hostname: hostname() }), {
731
+ return withMigrationLockGuard(path, async () => {
732
+ const token = JSON.stringify({
733
+ token: randomUUID(),
734
+ pid: process.pid,
735
+ hostname: hostname(),
736
+ createdAt: new Date().toISOString(),
737
+ });
738
+ const writeOwnedLock = async () => {
739
+ await writeFile(path, token, {
680
740
  flag: 'wx',
681
741
  mode: 0o600,
682
742
  });
683
- return () => rm(path, { force: true });
743
+ };
744
+ try {
745
+ await writeOwnedLock();
684
746
  }
685
747
  catch (error) {
686
- if (attempt === 0 && (await removeStaleMigrationLock(path))) {
687
- continue;
748
+ if (!(await removeStaleMigrationLock(path))) {
749
+ throw new SddCoreV6MigrationError('MIGRATION_BUSY', 'another migration owns the lock', {
750
+ cause: error,
751
+ });
688
752
  }
689
- throw new SddCoreV6MigrationError('MIGRATION_BUSY', 'another migration owns the lock', {
690
- cause: error,
691
- });
753
+ await writeOwnedLock();
692
754
  }
693
- }
694
- throw new SddCoreV6MigrationError('MIGRATION_BUSY', 'migration lock could not be acquired');
755
+ return () => withMigrationLockGuard(path, async () => {
756
+ if ((await readTextIfPresent(path)) === token) {
757
+ await rm(path, { force: true });
758
+ }
759
+ });
760
+ });
695
761
  }
696
762
  /** Offline, fail-closed migration of every catalog family into the SDD-core v6 boundary. */
697
- // eslint-disable-next-line max-lines-per-function -- top-level saga keeps phase order explicit
763
+ // eslint-disable-next-line max-lines-per-function, complexity -- top-level saga keeps phase order explicit
698
764
  export async function ensureSddCoreV6Storage(options = {}) {
699
765
  const layout = options.layout ?? resolveSddCoreV6StorageLayout();
766
+ const completedBeforeLock = await readCompletionMarker(layout);
767
+ if (completedBeforeLock) {
768
+ await quarantineIncidentalSidecars(layout, options.inspectOpenHandles ?? defaultOpenHandleInspector);
769
+ await verifyCompleted(layout, completedBeforeLock);
770
+ const journal = (await readJsonObject(layout.sddCoreV6Journal));
771
+ return {
772
+ status: 'verified',
773
+ markerPath: layout.sddCoreV6Marker,
774
+ journalPath: layout.sddCoreV6Journal,
775
+ families: journal.families,
776
+ };
777
+ }
700
778
  const release = await acquireMigrationLock(layout);
701
779
  try {
702
780
  const marker = await readCompletionMarker(layout);
@@ -8,6 +8,7 @@ import { resolveStorageLayout } from './storage-layout.js';
8
8
  import { addProject, getCanonicalRoot, getProjects, readLogicalProjectId, } from './global-projects-store.js';
9
9
  // eslint-disable-next-line no-restricted-imports -- grandfathered layer violation, remediation SPEC-1661 SPEC-1662 SPEC-1663
10
10
  import { isEphemeralProject } from '../engine/data-projects-gc/pattern-matcher.js';
11
+ import { reportClassifiedDegradation } from '../errors/classified-degradation.js';
11
12
  const IDENTITY_VERSION = 1;
12
13
  const execFileAsync = promisify(execFile);
13
14
  const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
@@ -274,7 +275,8 @@ async function committedLogicalProjectId(root) {
274
275
  const parsed = JSON.parse(raw);
275
276
  return isProjectIdentity(parsed) ? parsed.logicalProjectId : undefined;
276
277
  }
277
- catch {
278
+ catch (error) {
279
+ reportClassifiedDegradation('COMMITTED_PROJECT_ID_UNAVAILABLE', error);
278
280
  return undefined;
279
281
  }
280
282
  }
@@ -287,7 +289,8 @@ async function gitCommonDirectory(root) {
287
289
  const common = await gitValue(root, ['rev-parse', '--git-common-dir']);
288
290
  return await normalizePathBestEffort(isAbsolute(common) ? common : resolve(root, common));
289
291
  }
290
- catch {
292
+ catch (error) {
293
+ reportClassifiedDegradation('GIT_COMMON_DIRECTORY_UNAVAILABLE', error);
291
294
  return undefined;
292
295
  }
293
296
  }
@@ -392,6 +395,19 @@ export async function resolvePortableSpecPath(specId, storedPath, canonicalRoot)
392
395
  */
393
396
  export async function resolveVerifiedSpecPath(specId, storedPath, canonicalRoot) {
394
397
  const root = resolve(canonicalRoot);
398
+ let rootStat;
399
+ try {
400
+ rootStat = await lstat(root);
401
+ }
402
+ catch (error) {
403
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
404
+ throw new PortablePathError('ROOT_NOT_FOUND', '[Planu] canonical root was not found');
405
+ }
406
+ throw error;
407
+ }
408
+ if (rootStat.isSymbolicLink()) {
409
+ throw new PortablePathError('ROOT_UNVERIFIED', '[Planu] canonical root must not be a symlink');
410
+ }
395
411
  const failure = await verifyCanonicalRoot(root);
396
412
  if (failure) {
397
413
  const registered = failure.roots.length > 0 ? `, registered=[${failure.roots.join(', ')}]` : '';