@codeledger/cli 0.8.8 → 0.8.9
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/ambient-activation.d.ts +30 -0
- package/dist/ambient-activation.d.ts.map +1 -0
- package/dist/ambient-activation.js +449 -0
- package/dist/ambient-activation.js.map +1 -0
- package/dist/command-activation.d.ts +2 -9
- package/dist/command-activation.d.ts.map +1 -1
- package/dist/command-activation.js +1 -104
- package/dist/command-activation.js.map +1 -1
- package/dist/commands/about.d.ts +2 -0
- package/dist/commands/about.d.ts.map +1 -0
- package/dist/commands/about.js +18 -0
- package/dist/commands/about.js.map +1 -0
- package/dist/commands/apply-policy.d.ts.map +1 -1
- package/dist/commands/apply-policy.js +14 -0
- package/dist/commands/apply-policy.js.map +1 -1
- package/dist/commands/audit-export.d.ts.map +1 -1
- package/dist/commands/audit-export.js +3 -1
- package/dist/commands/audit-export.js.map +1 -1
- package/dist/commands/audit.d.ts +1 -1
- package/dist/commands/audit.js +153 -2
- package/dist/commands/audit.js.map +1 -1
- package/dist/commands/auto-refresh.d.ts +7 -0
- package/dist/commands/auto-refresh.d.ts.map +1 -1
- package/dist/commands/auto-refresh.js +30 -10
- package/dist/commands/auto-refresh.js.map +1 -1
- package/dist/commands/broker.d.ts.map +1 -1
- package/dist/commands/broker.js +24 -14
- package/dist/commands/broker.js.map +1 -1
- package/dist/commands/bundle.d.ts.map +1 -1
- package/dist/commands/bundle.js +30 -1
- package/dist/commands/bundle.js.map +1 -1
- package/dist/commands/ci.d.ts.map +1 -1
- package/dist/commands/ci.js +34 -2
- package/dist/commands/ci.js.map +1 -1
- package/dist/commands/complete-check.d.ts.map +1 -1
- package/dist/commands/complete-check.js +23 -0
- package/dist/commands/complete-check.js.map +1 -1
- package/dist/commands/context.d.ts.map +1 -1
- package/dist/commands/context.js +26 -3
- package/dist/commands/context.js.map +1 -1
- package/dist/commands/coordination.d.ts +6 -0
- package/dist/commands/coordination.d.ts.map +1 -0
- package/dist/commands/coordination.js +177 -0
- package/dist/commands/coordination.js.map +1 -0
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +7 -1
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/insight-seed.d.ts +2 -0
- package/dist/commands/insight-seed.d.ts.map +1 -0
- package/dist/commands/insight-seed.js +59 -0
- package/dist/commands/insight-seed.js.map +1 -0
- package/dist/commands/insight-smoke-test.d.ts +2 -0
- package/dist/commands/insight-smoke-test.d.ts.map +1 -0
- package/dist/commands/insight-smoke-test.js +44 -0
- package/dist/commands/insight-smoke-test.js.map +1 -0
- package/dist/commands/insight.d.ts +2 -0
- package/dist/commands/insight.d.ts.map +1 -0
- package/dist/commands/insight.js +182 -0
- package/dist/commands/insight.js.map +1 -0
- package/dist/commands/intent.js +2 -2
- package/dist/commands/intent.js.map +1 -1
- package/dist/commands/ledger.js +10 -2
- package/dist/commands/ledger.js.map +1 -1
- package/dist/commands/license.d.ts.map +1 -1
- package/dist/commands/license.js +5 -5
- package/dist/commands/license.js.map +1 -1
- package/dist/commands/memory.d.ts.map +1 -1
- package/dist/commands/memory.js +168 -0
- package/dist/commands/memory.js.map +1 -1
- package/dist/commands/provenance.d.ts.map +1 -1
- package/dist/commands/provenance.js +20 -4
- package/dist/commands/provenance.js.map +1 -1
- package/dist/commands/scan.d.ts +1 -1
- package/dist/commands/scan.d.ts.map +1 -1
- package/dist/commands/scan.js +268 -31
- package/dist/commands/scan.js.map +1 -1
- package/dist/commands/serve.d.ts.map +1 -1
- package/dist/commands/serve.js +238 -66
- package/dist/commands/serve.js.map +1 -1
- package/dist/commands/session-cleanup.d.ts.map +1 -1
- package/dist/commands/session-cleanup.js +2 -0
- package/dist/commands/session-cleanup.js.map +1 -1
- package/dist/commands/team-ledger.d.ts.map +1 -1
- package/dist/commands/team-ledger.js +4 -1
- package/dist/commands/team-ledger.js.map +1 -1
- package/dist/commands/verify.d.ts.map +1 -1
- package/dist/commands/verify.js +32 -0
- package/dist/commands/verify.js.map +1 -1
- package/dist/coordination/index.d.ts +69 -0
- package/dist/coordination/index.d.ts.map +1 -0
- package/dist/coordination/index.js +1093 -0
- package/dist/coordination/index.js.map +1 -0
- package/dist/health/dashboard.d.ts.map +1 -1
- package/dist/health/dashboard.js +3 -1
- package/dist/health/dashboard.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +162 -30
- package/dist/index.js.map +1 -1
- package/dist/insight/telemetry.d.ts +14 -0
- package/dist/insight/telemetry.d.ts.map +1 -0
- package/dist/insight/telemetry.js +87 -0
- package/dist/insight/telemetry.js.map +1 -0
- package/dist/intake/candidate-paths/CandidatePathDetector.d.ts +5 -0
- package/dist/intake/candidate-paths/CandidatePathDetector.d.ts.map +1 -0
- package/dist/intake/candidate-paths/CandidatePathDetector.js +173 -0
- package/dist/intake/candidate-paths/CandidatePathDetector.js.map +1 -0
- package/dist/intake/candidate-paths/anchorRadiusExpansion.d.ts +4 -0
- package/dist/intake/candidate-paths/anchorRadiusExpansion.d.ts.map +1 -0
- package/dist/intake/candidate-paths/anchorRadiusExpansion.js +66 -0
- package/dist/intake/candidate-paths/anchorRadiusExpansion.js.map +1 -0
- package/dist/intake/candidate-paths/applyNegativeFiltering.d.ts +4 -0
- package/dist/intake/candidate-paths/applyNegativeFiltering.d.ts.map +1 -0
- package/dist/intake/candidate-paths/applyNegativeFiltering.js +24 -0
- package/dist/intake/candidate-paths/applyNegativeFiltering.js.map +1 -0
- package/dist/intake/candidate-paths/coCommitAnalyzer.d.ts +3 -0
- package/dist/intake/candidate-paths/coCommitAnalyzer.d.ts.map +1 -0
- package/dist/intake/candidate-paths/coCommitAnalyzer.js +27 -0
- package/dist/intake/candidate-paths/coCommitAnalyzer.js.map +1 -0
- package/dist/intake/candidate-paths/computeConfidence.d.ts +3 -0
- package/dist/intake/candidate-paths/computeConfidence.d.ts.map +1 -0
- package/dist/intake/candidate-paths/computeConfidence.js +14 -0
- package/dist/intake/candidate-paths/computeConfidence.js.map +1 -0
- package/dist/intake/candidate-paths/consolidateCandidates.d.ts +5 -0
- package/dist/intake/candidate-paths/consolidateCandidates.d.ts.map +1 -0
- package/dist/intake/candidate-paths/consolidateCandidates.js +61 -0
- package/dist/intake/candidate-paths/consolidateCandidates.js.map +1 -0
- package/dist/intake/candidate-paths/hierarchicalMatching.d.ts +7 -0
- package/dist/intake/candidate-paths/hierarchicalMatching.d.ts.map +1 -0
- package/dist/intake/candidate-paths/hierarchicalMatching.js +46 -0
- package/dist/intake/candidate-paths/hierarchicalMatching.js.map +1 -0
- package/dist/intake/candidate-paths/integration.d.ts +7 -0
- package/dist/intake/candidate-paths/integration.d.ts.map +1 -0
- package/dist/intake/candidate-paths/integration.js +63 -0
- package/dist/intake/candidate-paths/integration.js.map +1 -0
- package/dist/intake/candidate-paths/pathDetectionOverrides.d.ts +3 -0
- package/dist/intake/candidate-paths/pathDetectionOverrides.d.ts.map +1 -0
- package/dist/intake/candidate-paths/pathDetectionOverrides.js +134 -0
- package/dist/intake/candidate-paths/pathDetectionOverrides.js.map +1 -0
- package/dist/intake/candidate-paths/repoIndexAdapter.d.ts +4 -0
- package/dist/intake/candidate-paths/repoIndexAdapter.d.ts.map +1 -0
- package/dist/intake/candidate-paths/repoIndexAdapter.js +99 -0
- package/dist/intake/candidate-paths/repoIndexAdapter.js.map +1 -0
- package/dist/intake/candidate-paths/resolveExplicitTargets.d.ts +8 -0
- package/dist/intake/candidate-paths/resolveExplicitTargets.d.ts.map +1 -0
- package/dist/intake/candidate-paths/resolveExplicitTargets.js +65 -0
- package/dist/intake/candidate-paths/resolveExplicitTargets.js.map +1 -0
- package/dist/intake/candidate-paths/rules.d.ts +13 -0
- package/dist/intake/candidate-paths/rules.d.ts.map +1 -0
- package/dist/intake/candidate-paths/rules.js +64 -0
- package/dist/intake/candidate-paths/rules.js.map +1 -0
- package/dist/intake/candidate-paths/scoreIntentSurfaceMatches.d.ts +10 -0
- package/dist/intake/candidate-paths/scoreIntentSurfaceMatches.d.ts.map +1 -0
- package/dist/intake/candidate-paths/scoreIntentSurfaceMatches.js +73 -0
- package/dist/intake/candidate-paths/scoreIntentSurfaceMatches.js.map +1 -0
- package/dist/intake/candidate-paths/shapeEstimator.d.ts +3 -0
- package/dist/intake/candidate-paths/shapeEstimator.d.ts.map +1 -0
- package/dist/intake/candidate-paths/shapeEstimator.js +17 -0
- package/dist/intake/candidate-paths/shapeEstimator.js.map +1 -0
- package/dist/intake/candidate-paths/types.d.ts +148 -0
- package/dist/intake/candidate-paths/types.d.ts.map +1 -0
- package/dist/intake/candidate-paths/types.js +2 -0
- package/dist/intake/candidate-paths/types.js.map +1 -0
- package/dist/intake/task-classifier/TaskClassifier.d.ts +5 -0
- package/dist/intake/task-classifier/TaskClassifier.d.ts.map +1 -0
- package/dist/intake/task-classifier/TaskClassifier.js +96 -0
- package/dist/intake/task-classifier/TaskClassifier.js.map +1 -0
- package/dist/intake/task-classifier/applyOverrides.d.ts +3 -0
- package/dist/intake/task-classifier/applyOverrides.d.ts.map +1 -0
- package/dist/intake/task-classifier/applyOverrides.js +55 -0
- package/dist/intake/task-classifier/applyOverrides.js.map +1 -0
- package/dist/intake/task-classifier/computeConfidence.d.ts +3 -0
- package/dist/intake/task-classifier/computeConfidence.d.ts.map +1 -0
- package/dist/intake/task-classifier/computeConfidence.js +13 -0
- package/dist/intake/task-classifier/computeConfidence.js.map +1 -0
- package/dist/intake/task-classifier/deriveRiskAndComplexity.d.ts +4 -0
- package/dist/intake/task-classifier/deriveRiskAndComplexity.d.ts.map +1 -0
- package/dist/intake/task-classifier/deriveRiskAndComplexity.js +24 -0
- package/dist/intake/task-classifier/deriveRiskAndComplexity.js.map +1 -0
- package/dist/intake/task-classifier/deriveTags.d.ts +3 -0
- package/dist/intake/task-classifier/deriveTags.d.ts.map +1 -0
- package/dist/intake/task-classifier/deriveTags.js +43 -0
- package/dist/intake/task-classifier/deriveTags.js.map +1 -0
- package/dist/intake/task-classifier/index.d.ts +6 -0
- package/dist/intake/task-classifier/index.d.ts.map +1 -0
- package/dist/intake/task-classifier/index.js +6 -0
- package/dist/intake/task-classifier/index.js.map +1 -0
- package/dist/intake/task-classifier/mergeScores.d.ts +4 -0
- package/dist/intake/task-classifier/mergeScores.d.ts.map +1 -0
- package/dist/intake/task-classifier/mergeScores.js +68 -0
- package/dist/intake/task-classifier/mergeScores.js.map +1 -0
- package/dist/intake/task-classifier/pathMatching.d.ts +3 -0
- package/dist/intake/task-classifier/pathMatching.d.ts.map +1 -0
- package/dist/intake/task-classifier/pathMatching.js +33 -0
- package/dist/intake/task-classifier/pathMatching.js.map +1 -0
- package/dist/intake/task-classifier/rules.d.ts +28 -0
- package/dist/intake/task-classifier/rules.d.ts.map +1 -0
- package/dist/intake/task-classifier/rules.js +138 -0
- package/dist/intake/task-classifier/rules.js.map +1 -0
- package/dist/intake/task-classifier/scoreKeywords.d.ts +5 -0
- package/dist/intake/task-classifier/scoreKeywords.d.ts.map +1 -0
- package/dist/intake/task-classifier/scoreKeywords.js +41 -0
- package/dist/intake/task-classifier/scoreKeywords.js.map +1 -0
- package/dist/intake/task-classifier/scoreMetadata.d.ts +3 -0
- package/dist/intake/task-classifier/scoreMetadata.d.ts.map +1 -0
- package/dist/intake/task-classifier/scoreMetadata.js +29 -0
- package/dist/intake/task-classifier/scoreMetadata.js.map +1 -0
- package/dist/intake/task-classifier/scorePaths.d.ts +3 -0
- package/dist/intake/task-classifier/scorePaths.d.ts.map +1 -0
- package/dist/intake/task-classifier/scorePaths.js +38 -0
- package/dist/intake/task-classifier/scorePaths.js.map +1 -0
- package/dist/intake/task-classifier/types.d.ts +51 -0
- package/dist/intake/task-classifier/types.d.ts.map +1 -0
- package/dist/intake/task-classifier/types.js +2 -0
- package/dist/intake/task-classifier/types.js.map +1 -0
- package/dist/memory/TaskClassifier.d.ts +6 -0
- package/dist/memory/TaskClassifier.d.ts.map +1 -0
- package/dist/memory/TaskClassifier.js +344 -0
- package/dist/memory/TaskClassifier.js.map +1 -0
- package/dist/memory/context-injection.d.ts +12 -0
- package/dist/memory/context-injection.d.ts.map +1 -0
- package/dist/memory/context-injection.js +548 -0
- package/dist/memory/context-injection.js.map +1 -0
- package/dist/memory/index.d.ts +2 -0
- package/dist/memory/index.d.ts.map +1 -1
- package/dist/memory/index.js +2 -0
- package/dist/memory/index.js.map +1 -1
- package/dist/memory/policy-artifacts.d.ts +31 -0
- package/dist/memory/policy-artifacts.d.ts.map +1 -0
- package/dist/memory/policy-artifacts.js +614 -0
- package/dist/memory/policy-artifacts.js.map +1 -0
- package/dist/memory/preamble.d.ts.map +1 -1
- package/dist/memory/preamble.js +10 -0
- package/dist/memory/preamble.js.map +1 -1
- package/dist/memory/taskClassifierOverrides.d.ts +3 -0
- package/dist/memory/taskClassifierOverrides.d.ts.map +1 -0
- package/dist/memory/taskClassifierOverrides.js +153 -0
- package/dist/memory/taskClassifierOverrides.js.map +1 -0
- package/dist/memory/taskClassifierRules.d.ts +15 -0
- package/dist/memory/taskClassifierRules.d.ts.map +1 -0
- package/dist/memory/taskClassifierRules.js +277 -0
- package/dist/memory/taskClassifierRules.js.map +1 -0
- package/dist/memory/taskClassifierTypes.d.ts +40 -0
- package/dist/memory/taskClassifierTypes.d.ts.map +1 -0
- package/dist/memory/taskClassifierTypes.js +2 -0
- package/dist/memory/taskClassifierTypes.js.map +1 -0
- package/dist/onboarding.js +5 -5
- package/dist/onboarding.js.map +1 -1
- package/dist/protected-runtime/core.d.ts +7 -0
- package/dist/protected-runtime/core.d.ts.map +1 -0
- package/dist/protected-runtime/core.js +24 -0
- package/dist/protected-runtime/core.js.map +1 -0
- package/dist/protected-runtime/module-loader.d.ts +9 -0
- package/dist/protected-runtime/module-loader.d.ts.map +1 -0
- package/dist/protected-runtime/module-loader.js +68 -0
- package/dist/protected-runtime/module-loader.js.map +1 -0
- package/dist/protected-shell.d.ts +2 -0
- package/dist/protected-shell.d.ts.map +1 -0
- package/dist/protected-shell.js +50 -0
- package/dist/protected-shell.js.map +1 -0
- package/dist/risk-detection/heuristics.js +1 -1
- package/dist/risk-detection/heuristics.js.map +1 -1
- package/dist/security/export-sanitizer.d.ts +76 -0
- package/dist/security/export-sanitizer.d.ts.map +1 -0
- package/dist/security/export-sanitizer.js +176 -0
- package/dist/security/export-sanitizer.js.map +1 -0
- package/dist/security/path-summary.d.ts +4 -0
- package/dist/security/path-summary.d.ts.map +1 -0
- package/dist/security/path-summary.js +94 -0
- package/dist/security/path-summary.js.map +1 -0
- package/dist/templates/config.d.ts.map +1 -1
- package/dist/templates/config.js +59 -0
- package/dist/templates/config.js.map +1 -1
- package/package.json +17 -13
|
@@ -0,0 +1,1093 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
3
|
+
import { dirname, join, relative, resolve } from 'node:path';
|
|
4
|
+
import { execSync } from 'node:child_process';
|
|
5
|
+
import { defaultConfig } from '../templates/config.js';
|
|
6
|
+
import { appendDecisionEvent, newTimelineCommandId } from '../session-timeline.js';
|
|
7
|
+
const COORDINATION_DIR = join('.codeledger', 'coordination');
|
|
8
|
+
const LEASES_PATH = join(COORDINATION_DIR, 'leases.json');
|
|
9
|
+
const EVENTS_PATH = join(COORDINATION_DIR, 'events.jsonl');
|
|
10
|
+
const VALIDATIONS_PATH = join(COORDINATION_DIR, 'validations.jsonl');
|
|
11
|
+
const LOCK_TIMEOUT_MS = 5_000;
|
|
12
|
+
const LOCK_RETRY_MS = 50;
|
|
13
|
+
const OWNERSHIP_TERMS = ['auth', 'token', 'jwt', 'login', 'session', 'migration', 'migrations', 'schema', 'db', 'routes', 'route', 'handlers', 'handler', 'api', 'infra', 'deploy', 'config', 'workflow', 'workflows', 'test', 'tests'];
|
|
14
|
+
const GENERIC_OWNERSHIP_FILES = new Set(['index.ts', 'types.ts', 'validation.ts', 'config.ts', 'helpers.ts', 'logger.ts', 'errors.ts']);
|
|
15
|
+
const MAX_SHARED_NEIGHBOR_DEGREE = 8;
|
|
16
|
+
export function claimPaths(cwd, rawPaths, options) {
|
|
17
|
+
return withState(cwd, (state) => {
|
|
18
|
+
const now = new Date();
|
|
19
|
+
const config = loadCoordinationConfig(cwd);
|
|
20
|
+
const repoFingerprint = computeRepoFingerprint(cwd);
|
|
21
|
+
const commitHash = getCommitHash(cwd);
|
|
22
|
+
const sessionLookup = loadSessionLookup(cwd);
|
|
23
|
+
const refresh = refreshLeaseStatuses(state.leases, sessionLookup, config, now);
|
|
24
|
+
appendTransitionEvents(cwd, refresh.transitions, now);
|
|
25
|
+
appendHeartbeatEvents(cwd, refresh.heartbeats, now, 'session_registry_heartbeat');
|
|
26
|
+
const scopes = buildScopes(cwd, rawPaths);
|
|
27
|
+
const sameSessionOverlaps = options.sessionId
|
|
28
|
+
? state.leases
|
|
29
|
+
.filter((lease) => lease.session_id === options.sessionId && lease.status === 'active')
|
|
30
|
+
.filter((lease) => hasAnyOverlap(scopes, lease.scopes).length > 0)
|
|
31
|
+
.sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id))
|
|
32
|
+
: [];
|
|
33
|
+
if (sameSessionOverlaps.length > 0) {
|
|
34
|
+
const primary = sameSessionOverlaps[0];
|
|
35
|
+
const mergedScopes = dedupeScopes([
|
|
36
|
+
...primary.scopes,
|
|
37
|
+
...sameSessionOverlaps.slice(1).flatMap((lease) => lease.scopes),
|
|
38
|
+
...scopes,
|
|
39
|
+
]);
|
|
40
|
+
const mergedTtl = Math.max(primary.ttl_seconds, options.ttlSeconds, config.heartbeat_extension_seconds);
|
|
41
|
+
const mergedLease = {
|
|
42
|
+
...primary,
|
|
43
|
+
actor: options.actor || primary.actor,
|
|
44
|
+
task: options.task ?? primary.task,
|
|
45
|
+
mode: primary.mode === 'exclusive' || options.mode === 'exclusive' ? 'exclusive' : 'shared',
|
|
46
|
+
updated_at: now.toISOString(),
|
|
47
|
+
last_heartbeat_at: now.toISOString(),
|
|
48
|
+
expires_at: new Date(now.getTime() + mergedTtl * 1000).toISOString(),
|
|
49
|
+
ttl_seconds: mergedTtl,
|
|
50
|
+
repo_fingerprint: repoFingerprint,
|
|
51
|
+
commit_hash: commitHash,
|
|
52
|
+
scopes: mergedScopes,
|
|
53
|
+
claimed_paths: mergedScopes.map((scope) => scope.path),
|
|
54
|
+
status: 'active',
|
|
55
|
+
status_reason: 'lease_reclaimed',
|
|
56
|
+
};
|
|
57
|
+
const assessment = assessLeaseRequest(mergedLease, state.leases, config.policy_mode);
|
|
58
|
+
const overridden = options.force && assessment.decision === 'block';
|
|
59
|
+
if (assessment.decision === 'block' && !overridden) {
|
|
60
|
+
throw new CoordinationBlockedError(assessment.reason, assessment);
|
|
61
|
+
}
|
|
62
|
+
if (overridden) {
|
|
63
|
+
mergedLease.force_overridden = true;
|
|
64
|
+
mergedLease.overridden_claim_ids = assessment.conflicting_claim_ids;
|
|
65
|
+
mergedLease.conflicting_session_ids = assessment.conflicting_session_ids;
|
|
66
|
+
mergedLease.status_reason = 'lease_force_overridden';
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
mergedLease.force_overridden = false;
|
|
70
|
+
mergedLease.overridden_claim_ids = [];
|
|
71
|
+
mergedLease.conflicting_session_ids = [];
|
|
72
|
+
}
|
|
73
|
+
Object.assign(primary, mergedLease);
|
|
74
|
+
const mergedAway = sameSessionOverlaps.slice(1);
|
|
75
|
+
for (const redundant of mergedAway) {
|
|
76
|
+
redundant.status = 'released';
|
|
77
|
+
redundant.updated_at = now.toISOString();
|
|
78
|
+
redundant.last_status_change_at = now.toISOString();
|
|
79
|
+
redundant.status_reason = `merged_into_session_claim:${primary.id}`;
|
|
80
|
+
redundant.released_at = now.toISOString();
|
|
81
|
+
redundant.released_reason = redundant.status_reason;
|
|
82
|
+
appendEvent(cwd, {
|
|
83
|
+
schema_version: 'coordination-event/v2',
|
|
84
|
+
type: 'lease_released',
|
|
85
|
+
timestamp: now.toISOString(),
|
|
86
|
+
session_id: redundant.session_id,
|
|
87
|
+
actor: redundant.actor,
|
|
88
|
+
lease: { ...redundant },
|
|
89
|
+
reason: redundant.status_reason,
|
|
90
|
+
from_status: 'active',
|
|
91
|
+
to_status: 'released',
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
appendEvent(cwd, {
|
|
95
|
+
schema_version: 'coordination-event/v2',
|
|
96
|
+
type: 'lease_reclaimed',
|
|
97
|
+
timestamp: now.toISOString(),
|
|
98
|
+
session_id: options.sessionId,
|
|
99
|
+
actor: options.actor,
|
|
100
|
+
lease: { ...primary },
|
|
101
|
+
assessment,
|
|
102
|
+
overridden,
|
|
103
|
+
});
|
|
104
|
+
if (overridden) {
|
|
105
|
+
appendEvent(cwd, {
|
|
106
|
+
schema_version: 'coordination-event/v2',
|
|
107
|
+
type: 'lease_force_overridden',
|
|
108
|
+
timestamp: now.toISOString(),
|
|
109
|
+
session_id: options.sessionId,
|
|
110
|
+
actor: options.actor,
|
|
111
|
+
lease: { ...primary },
|
|
112
|
+
assessment,
|
|
113
|
+
overridden_claim_ids: assessment.conflicting_claim_ids,
|
|
114
|
+
conflicting_session_ids: assessment.conflicting_session_ids,
|
|
115
|
+
policy_decision: assessment.policy_decision,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
appendTimelineDecision(cwd, options.sessionId, overridden ? 'coordination_override' : 'coordination_claim', {
|
|
119
|
+
lease_id: primary.id,
|
|
120
|
+
policy_mode: config.policy_mode,
|
|
121
|
+
decision: overridden ? 'override' : assessment.decision,
|
|
122
|
+
paths: primary.claimed_paths,
|
|
123
|
+
reason: assessment.reason,
|
|
124
|
+
});
|
|
125
|
+
return { state, result: { lease: { ...primary }, assessment, overridden } };
|
|
126
|
+
}
|
|
127
|
+
const heartbeats = options.sessionId
|
|
128
|
+
? touchSessionLeases(state.leases, options.sessionId, config.heartbeat_extension_seconds, now, 'claim_heartbeat')
|
|
129
|
+
: [];
|
|
130
|
+
appendHeartbeatEvents(cwd, heartbeats, now, 'claim_heartbeat');
|
|
131
|
+
const lease = {
|
|
132
|
+
id: `lease_${randomUUID().slice(0, 8)}`,
|
|
133
|
+
session_id: options.sessionId ?? 'no-session',
|
|
134
|
+
actor: options.actor,
|
|
135
|
+
task: options.task,
|
|
136
|
+
mode: options.mode,
|
|
137
|
+
created_at: now.toISOString(),
|
|
138
|
+
updated_at: now.toISOString(),
|
|
139
|
+
last_heartbeat_at: now.toISOString(),
|
|
140
|
+
expires_at: new Date(now.getTime() + options.ttlSeconds * 1000).toISOString(),
|
|
141
|
+
ttl_seconds: options.ttlSeconds,
|
|
142
|
+
repo_fingerprint: repoFingerprint,
|
|
143
|
+
commit_hash: commitHash,
|
|
144
|
+
claimed_paths: scopes.map((scope) => scope.path),
|
|
145
|
+
scopes,
|
|
146
|
+
status: 'active',
|
|
147
|
+
status_reason: 'lease_claimed',
|
|
148
|
+
last_status_change_at: now.toISOString(),
|
|
149
|
+
};
|
|
150
|
+
const assessment = assessLeaseRequest(lease, state.leases, config.policy_mode);
|
|
151
|
+
const overridden = options.force && assessment.decision === 'block';
|
|
152
|
+
if (assessment.decision === 'block' && !overridden) {
|
|
153
|
+
throw new CoordinationBlockedError(assessment.reason, assessment);
|
|
154
|
+
}
|
|
155
|
+
if (overridden) {
|
|
156
|
+
lease.force_overridden = true;
|
|
157
|
+
lease.overridden_claim_ids = assessment.conflicting_claim_ids;
|
|
158
|
+
lease.conflicting_session_ids = assessment.conflicting_session_ids;
|
|
159
|
+
lease.status_reason = 'lease_force_overridden';
|
|
160
|
+
}
|
|
161
|
+
state.leases.push(lease);
|
|
162
|
+
appendEvent(cwd, {
|
|
163
|
+
schema_version: 'coordination-event/v2',
|
|
164
|
+
type: 'lease_claimed',
|
|
165
|
+
timestamp: now.toISOString(),
|
|
166
|
+
session_id: options.sessionId,
|
|
167
|
+
actor: options.actor,
|
|
168
|
+
lease,
|
|
169
|
+
assessment,
|
|
170
|
+
overridden,
|
|
171
|
+
});
|
|
172
|
+
if (overridden) {
|
|
173
|
+
appendEvent(cwd, {
|
|
174
|
+
schema_version: 'coordination-event/v2',
|
|
175
|
+
type: 'lease_force_overridden',
|
|
176
|
+
timestamp: now.toISOString(),
|
|
177
|
+
session_id: options.sessionId,
|
|
178
|
+
actor: options.actor,
|
|
179
|
+
lease,
|
|
180
|
+
assessment,
|
|
181
|
+
overridden_claim_ids: assessment.conflicting_claim_ids,
|
|
182
|
+
conflicting_session_ids: assessment.conflicting_session_ids,
|
|
183
|
+
policy_decision: assessment.policy_decision,
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
appendTimelineDecision(cwd, options.sessionId, overridden ? 'coordination_override' : 'coordination_claim', {
|
|
187
|
+
lease_id: lease.id,
|
|
188
|
+
policy_mode: config.policy_mode,
|
|
189
|
+
decision: overridden ? 'override' : assessment.decision,
|
|
190
|
+
paths: lease.claimed_paths,
|
|
191
|
+
reason: assessment.reason,
|
|
192
|
+
});
|
|
193
|
+
return { state, result: { lease, assessment, overridden } };
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
export function listLeases(cwd, options = {}) {
|
|
197
|
+
return withState(cwd, (state) => {
|
|
198
|
+
const config = loadCoordinationConfig(cwd);
|
|
199
|
+
const sessionLookup = loadSessionLookup(cwd);
|
|
200
|
+
const now = new Date();
|
|
201
|
+
const refresh = refreshLeaseStatuses(state.leases, sessionLookup, config, now);
|
|
202
|
+
appendTransitionEvents(cwd, refresh.transitions, now);
|
|
203
|
+
appendHeartbeatEvents(cwd, refresh.heartbeats, now, 'session_registry_heartbeat');
|
|
204
|
+
const leases = state.leases
|
|
205
|
+
.filter((lease) => {
|
|
206
|
+
if (options.activeOnly)
|
|
207
|
+
return lease.status === 'active';
|
|
208
|
+
if (options.staleOnly)
|
|
209
|
+
return lease.status === 'stale' || lease.status === 'expired';
|
|
210
|
+
return true;
|
|
211
|
+
})
|
|
212
|
+
.sort(compareLeases);
|
|
213
|
+
return { state, result: leases };
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
export function preflightEdit(cwd, rawPath, options) {
|
|
217
|
+
return withState(cwd, (state) => {
|
|
218
|
+
const now = new Date();
|
|
219
|
+
const config = loadCoordinationConfig(cwd);
|
|
220
|
+
const sessionLookup = loadSessionLookup(cwd);
|
|
221
|
+
const refresh = refreshLeaseStatuses(state.leases, sessionLookup, config, now);
|
|
222
|
+
appendTransitionEvents(cwd, refresh.transitions, now);
|
|
223
|
+
appendHeartbeatEvents(cwd, refresh.heartbeats, now, 'session_registry_heartbeat');
|
|
224
|
+
const scopes = buildScopes(cwd, [rawPath]);
|
|
225
|
+
const syntheticLease = {
|
|
226
|
+
id: 'synthetic',
|
|
227
|
+
session_id: options.sessionId ?? 'no-session',
|
|
228
|
+
actor: 'preflight',
|
|
229
|
+
task: null,
|
|
230
|
+
mode: 'exclusive',
|
|
231
|
+
created_at: now.toISOString(),
|
|
232
|
+
updated_at: now.toISOString(),
|
|
233
|
+
last_heartbeat_at: now.toISOString(),
|
|
234
|
+
expires_at: now.toISOString(),
|
|
235
|
+
ttl_seconds: 0,
|
|
236
|
+
repo_fingerprint: computeRepoFingerprint(cwd),
|
|
237
|
+
commit_hash: getCommitHash(cwd),
|
|
238
|
+
claimed_paths: scopes.map((scope) => scope.path),
|
|
239
|
+
scopes,
|
|
240
|
+
status: 'active',
|
|
241
|
+
};
|
|
242
|
+
const selfCoveringLease = state.leases.find((lease) => lease.session_id === syntheticLease.session_id &&
|
|
243
|
+
lease.status === 'active' &&
|
|
244
|
+
hasAnyOverlap(scopes, lease.scopes).length > 0);
|
|
245
|
+
const rawAssessment = assessLeaseRequest(syntheticLease, state.leases, config.policy_mode);
|
|
246
|
+
let decision = rawAssessment.decision;
|
|
247
|
+
let reason = rawAssessment.reason;
|
|
248
|
+
if (decision === 'warn' && options.strict) {
|
|
249
|
+
decision = 'block';
|
|
250
|
+
reason = 'strict_mode_escalated_warning';
|
|
251
|
+
}
|
|
252
|
+
if (selfCoveringLease) {
|
|
253
|
+
decision = 'allow';
|
|
254
|
+
reason = 'covered_by_session_claim';
|
|
255
|
+
appendHeartbeatEvents(cwd, touchSessionLeases(state.leases, syntheticLease.session_id, config.heartbeat_extension_seconds, now, 'preflight_self_heartbeat'), now, 'preflight_self_heartbeat');
|
|
256
|
+
}
|
|
257
|
+
const record = {
|
|
258
|
+
id: `val_${randomUUID().slice(0, 8)}`,
|
|
259
|
+
timestamp: now.toISOString(),
|
|
260
|
+
session_id: options.sessionId,
|
|
261
|
+
path: scopes[0]?.path ?? normalizeRepoPath(cwd, rawPath),
|
|
262
|
+
repo_fingerprint: syntheticLease.repo_fingerprint,
|
|
263
|
+
commit_hash: syntheticLease.commit_hash,
|
|
264
|
+
claimed_scopes: scopes,
|
|
265
|
+
policy_mode: config.policy_mode,
|
|
266
|
+
decision,
|
|
267
|
+
strict: options.strict,
|
|
268
|
+
reason,
|
|
269
|
+
exact_overlap_count: rawAssessment.exact_overlap_count,
|
|
270
|
+
surface_overlap_count: rawAssessment.surface_overlap_count,
|
|
271
|
+
policy_decision: decision,
|
|
272
|
+
conflicting_claim_ids: rawAssessment.conflicting_claim_ids,
|
|
273
|
+
conflicting_session_ids: rawAssessment.conflicting_session_ids,
|
|
274
|
+
overlaps: rawAssessment.overlaps,
|
|
275
|
+
covered_by_self: Boolean(selfCoveringLease),
|
|
276
|
+
};
|
|
277
|
+
appendValidation(cwd, record);
|
|
278
|
+
appendEvent(cwd, {
|
|
279
|
+
schema_version: 'coordination-event/v2',
|
|
280
|
+
type: 'preflight_validated',
|
|
281
|
+
timestamp: now.toISOString(),
|
|
282
|
+
session_id: options.sessionId,
|
|
283
|
+
actor: 'preflight',
|
|
284
|
+
validation: record,
|
|
285
|
+
});
|
|
286
|
+
appendTimelineDecision(cwd, options.sessionId, 'coordination_preflight_edit', {
|
|
287
|
+
path: record.path,
|
|
288
|
+
decision,
|
|
289
|
+
reason,
|
|
290
|
+
exact_overlap_count: record.exact_overlap_count,
|
|
291
|
+
surface_overlap_count: record.surface_overlap_count,
|
|
292
|
+
});
|
|
293
|
+
return { state, result: record };
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
export function releaseLeases(cwd, options) {
|
|
297
|
+
return withState(cwd, (state) => {
|
|
298
|
+
const now = new Date();
|
|
299
|
+
const config = loadCoordinationConfig(cwd);
|
|
300
|
+
const sessionLookup = loadSessionLookup(cwd);
|
|
301
|
+
const refresh = refreshLeaseStatuses(state.leases, sessionLookup, config, now);
|
|
302
|
+
appendTransitionEvents(cwd, refresh.transitions, now);
|
|
303
|
+
appendHeartbeatEvents(cwd, refresh.heartbeats, now, 'session_registry_heartbeat');
|
|
304
|
+
const released = [];
|
|
305
|
+
const releasedLeases = [];
|
|
306
|
+
for (const lease of state.leases) {
|
|
307
|
+
if (lease.status === 'released')
|
|
308
|
+
continue;
|
|
309
|
+
if (options.all || (options.claimId && lease.id === options.claimId) || (options.sessionId && lease.session_id === options.sessionId)) {
|
|
310
|
+
const previousStatus = lease.status;
|
|
311
|
+
lease.status = 'released';
|
|
312
|
+
lease.updated_at = now.toISOString();
|
|
313
|
+
lease.last_status_change_at = now.toISOString();
|
|
314
|
+
lease.status_reason = options.all ? 'released_all' : options.claimId ? 'released_claim' : 'released_session';
|
|
315
|
+
lease.released_at = now.toISOString();
|
|
316
|
+
lease.released_reason = lease.status_reason;
|
|
317
|
+
released.push(lease.id);
|
|
318
|
+
releasedLeases.push({ ...lease });
|
|
319
|
+
appendEvent(cwd, {
|
|
320
|
+
schema_version: 'coordination-event/v2',
|
|
321
|
+
type: 'lease_released',
|
|
322
|
+
timestamp: now.toISOString(),
|
|
323
|
+
session_id: lease.session_id,
|
|
324
|
+
actor: lease.actor,
|
|
325
|
+
lease: { ...lease },
|
|
326
|
+
reason: lease.status_reason,
|
|
327
|
+
from_status: previousStatus,
|
|
328
|
+
to_status: 'released',
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
if (releasedLeases.length > 0) {
|
|
333
|
+
appendTimelineDecision(cwd, options.sessionId ?? null, 'coordination_release', {
|
|
334
|
+
released_claim_ids: released,
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
return { state, result: { released_claim_ids: released, total_released: released.length } };
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
export function buildCoordinationSummary(cwd) {
|
|
341
|
+
const leases = listLeases(cwd);
|
|
342
|
+
const config = loadCoordinationConfig(cwd);
|
|
343
|
+
const activeLeases = leases.filter((lease) => lease.status === 'active');
|
|
344
|
+
const staleLeases = leases.filter((lease) => lease.status === 'stale' || lease.status === 'expired');
|
|
345
|
+
const sessionIds = new Set(activeLeases.map((lease) => lease.session_id));
|
|
346
|
+
const overlaps = collectAllHotOverlaps(activeLeases);
|
|
347
|
+
const exactCount = overlaps.filter((overlap) => overlap.kind === 'exact_file').length;
|
|
348
|
+
const surfaceCount = overlaps.filter((overlap) => overlap.kind !== 'exact_file').length;
|
|
349
|
+
const surfaceCounts = new Map();
|
|
350
|
+
for (const lease of activeLeases) {
|
|
351
|
+
for (const scope of lease.scopes) {
|
|
352
|
+
surfaceCounts.set(scope.surface_key, (surfaceCounts.get(scope.surface_key) ?? 0) + 1);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
const topSurfaces = [...surfaceCounts.entries()]
|
|
356
|
+
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
|
357
|
+
.slice(0, 8)
|
|
358
|
+
.map(([surface_key, lease_count]) => ({ surface_key, lease_count }));
|
|
359
|
+
return {
|
|
360
|
+
policy_mode: config.policy_mode,
|
|
361
|
+
repo_fingerprint: computeRepoFingerprint(cwd),
|
|
362
|
+
active_sessions: sessionIds.size,
|
|
363
|
+
active_leases: activeLeases.length,
|
|
364
|
+
stale_leases: staleLeases.length,
|
|
365
|
+
exact_overlap_pairs: exactCount,
|
|
366
|
+
surface_overlap_pairs: surfaceCount,
|
|
367
|
+
top_surfaces: topSurfaces,
|
|
368
|
+
hot_overlaps: overlaps.slice(0, 12),
|
|
369
|
+
active_forced_overlaps: activeLeases
|
|
370
|
+
.filter((lease) => lease.force_overridden)
|
|
371
|
+
.sort(compareLeases)
|
|
372
|
+
.map((lease) => ({
|
|
373
|
+
lease_id: lease.id,
|
|
374
|
+
session_id: lease.session_id,
|
|
375
|
+
actor: lease.actor,
|
|
376
|
+
overridden_claim_ids: lease.overridden_claim_ids ?? [],
|
|
377
|
+
conflicting_session_ids: lease.conflicting_session_ids ?? [],
|
|
378
|
+
claimed_paths: lease.claimed_paths,
|
|
379
|
+
})),
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
export function loadCoordinationConfig(cwd) {
|
|
383
|
+
const path = join(cwd, '.codeledger', 'config.json');
|
|
384
|
+
const defaults = defaultConfig().coordination;
|
|
385
|
+
if (!existsSync(path))
|
|
386
|
+
return defaults;
|
|
387
|
+
try {
|
|
388
|
+
const parsed = JSON.parse(readFileSync(path, 'utf-8'));
|
|
389
|
+
return {
|
|
390
|
+
...defaults,
|
|
391
|
+
...(parsed.coordination ?? {}),
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
catch {
|
|
395
|
+
return defaults;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
export function computeRepoFingerprint(cwd) {
|
|
399
|
+
const repoRoot = gitOutput(cwd, 'git rev-parse --show-toplevel') ?? resolve(cwd);
|
|
400
|
+
const originUrl = gitOutput(cwd, 'git config --get remote.origin.url') ?? '';
|
|
401
|
+
const digest = createHash('sha256').update(`${repoRoot}\n${originUrl}`).digest('hex').slice(0, 12);
|
|
402
|
+
return `ws_${digest}`;
|
|
403
|
+
}
|
|
404
|
+
export function getCommitHash(cwd) {
|
|
405
|
+
return gitOutput(cwd, 'git rev-parse HEAD') ?? 'unknown';
|
|
406
|
+
}
|
|
407
|
+
export class CoordinationBlockedError extends Error {
|
|
408
|
+
assessment;
|
|
409
|
+
constructor(message, assessment) {
|
|
410
|
+
super(message);
|
|
411
|
+
this.name = 'CoordinationBlockedError';
|
|
412
|
+
this.assessment = assessment;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
function withState(cwd, fn) {
|
|
416
|
+
const unlock = acquireLock(cwd);
|
|
417
|
+
try {
|
|
418
|
+
const state = loadState(cwd);
|
|
419
|
+
const outcome = fn(state);
|
|
420
|
+
saveState(cwd, outcome.state);
|
|
421
|
+
return outcome.result;
|
|
422
|
+
}
|
|
423
|
+
finally {
|
|
424
|
+
unlock();
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
function loadState(cwd) {
|
|
428
|
+
const reconstructed = reconstructStateFromEvents(cwd);
|
|
429
|
+
if (reconstructed)
|
|
430
|
+
return reconstructed;
|
|
431
|
+
const path = join(cwd, LEASES_PATH);
|
|
432
|
+
if (!existsSync(path))
|
|
433
|
+
return { schema_version: 'coordination/v1', leases: [] };
|
|
434
|
+
try {
|
|
435
|
+
const parsed = JSON.parse(readFileSync(path, 'utf-8'));
|
|
436
|
+
if (parsed.schema_version === 'coordination/v1' && Array.isArray(parsed.leases)) {
|
|
437
|
+
bootstrapEventsFromState(cwd, parsed);
|
|
438
|
+
return parsed;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
catch {
|
|
442
|
+
// fall through
|
|
443
|
+
}
|
|
444
|
+
return { schema_version: 'coordination/v1', leases: [] };
|
|
445
|
+
}
|
|
446
|
+
function reconstructStateFromEvents(cwd) {
|
|
447
|
+
const path = join(cwd, EVENTS_PATH);
|
|
448
|
+
if (!existsSync(path))
|
|
449
|
+
return null;
|
|
450
|
+
try {
|
|
451
|
+
const rawLines = readFileSync(path, 'utf-8')
|
|
452
|
+
.split('\n')
|
|
453
|
+
.map((line) => line.trim())
|
|
454
|
+
.filter(Boolean);
|
|
455
|
+
const events = rawLines.map((line) => JSON.parse(line));
|
|
456
|
+
const leases = new Map();
|
|
457
|
+
let foundV2Event = false;
|
|
458
|
+
for (const event of events) {
|
|
459
|
+
if (event.schema_version !== 'coordination-event/v2')
|
|
460
|
+
continue;
|
|
461
|
+
foundV2Event = true;
|
|
462
|
+
if (event.type === 'lease_claimed'
|
|
463
|
+
|| event.type === 'lease_reclaimed'
|
|
464
|
+
|| event.type === 'lease_bootstrapped'
|
|
465
|
+
|| event.type === 'lease_force_overridden'
|
|
466
|
+
|| event.type === 'lease_heartbeat'
|
|
467
|
+
|| event.type === 'lease_released'
|
|
468
|
+
|| event.type === 'lease_status_changed') {
|
|
469
|
+
if (event.lease?.id) {
|
|
470
|
+
leases.set(event.lease.id, event.lease);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
if (!foundV2Event) {
|
|
475
|
+
const legacy = reconstructLegacyStateFromEvents(cwd, rawLines);
|
|
476
|
+
if (legacy)
|
|
477
|
+
return legacy;
|
|
478
|
+
return null;
|
|
479
|
+
}
|
|
480
|
+
return {
|
|
481
|
+
schema_version: 'coordination/v1',
|
|
482
|
+
leases: [...leases.values()].sort(compareLeases),
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
catch {
|
|
486
|
+
return null;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
function reconstructLegacyStateFromEvents(cwd, lines) {
|
|
490
|
+
const config = loadCoordinationConfig(cwd);
|
|
491
|
+
const leases = new Map();
|
|
492
|
+
let foundLegacy = false;
|
|
493
|
+
for (const line of lines) {
|
|
494
|
+
let event;
|
|
495
|
+
try {
|
|
496
|
+
event = JSON.parse(line);
|
|
497
|
+
}
|
|
498
|
+
catch {
|
|
499
|
+
continue;
|
|
500
|
+
}
|
|
501
|
+
if (!event?.type || !['claim', 'override', 'release', 'preflight_edit'].includes(event.type))
|
|
502
|
+
continue;
|
|
503
|
+
foundLegacy = true;
|
|
504
|
+
if ((event.type === 'claim' || event.type === 'override') && event.lease_id && event.claimed_paths?.length) {
|
|
505
|
+
const createdAt = event.timestamp;
|
|
506
|
+
const ttlSeconds = config.default_ttl_seconds;
|
|
507
|
+
const createdMs = new Date(createdAt).getTime();
|
|
508
|
+
const fallbackExpires = Number.isFinite(createdMs)
|
|
509
|
+
? new Date(createdMs + ttlSeconds * 1000).toISOString()
|
|
510
|
+
: createdAt;
|
|
511
|
+
const scopes = buildScopes(cwd, event.claimed_paths);
|
|
512
|
+
leases.set(event.lease_id, {
|
|
513
|
+
id: event.lease_id,
|
|
514
|
+
session_id: event.session_id ?? 'no-session',
|
|
515
|
+
actor: 'unknown',
|
|
516
|
+
task: null,
|
|
517
|
+
mode: 'exclusive',
|
|
518
|
+
created_at: createdAt,
|
|
519
|
+
updated_at: createdAt,
|
|
520
|
+
last_heartbeat_at: createdAt,
|
|
521
|
+
expires_at: fallbackExpires,
|
|
522
|
+
ttl_seconds: ttlSeconds,
|
|
523
|
+
repo_fingerprint: 'unknown',
|
|
524
|
+
commit_hash: 'unknown',
|
|
525
|
+
claimed_paths: scopes.map((scope) => scope.path),
|
|
526
|
+
scopes,
|
|
527
|
+
status: 'active',
|
|
528
|
+
status_reason: event.type === 'override' ? 'legacy_force_override_reconstructed' : 'legacy_claim_reconstructed',
|
|
529
|
+
last_status_change_at: createdAt,
|
|
530
|
+
force_overridden: event.type === 'override',
|
|
531
|
+
});
|
|
532
|
+
continue;
|
|
533
|
+
}
|
|
534
|
+
if (event.type === 'release') {
|
|
535
|
+
const toRelease = [...leases.values()].filter((lease) => event.claim_id
|
|
536
|
+
? lease.id === event.claim_id
|
|
537
|
+
: event.session_id
|
|
538
|
+
? lease.session_id === event.session_id
|
|
539
|
+
: true);
|
|
540
|
+
for (const lease of toRelease) {
|
|
541
|
+
lease.status = 'released';
|
|
542
|
+
lease.updated_at = event.timestamp;
|
|
543
|
+
lease.last_status_change_at = event.timestamp;
|
|
544
|
+
lease.status_reason = event.reason ?? 'legacy_release_reconstructed';
|
|
545
|
+
lease.released_at = event.timestamp;
|
|
546
|
+
lease.released_reason = event.reason ?? 'legacy_release_reconstructed';
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
if (!foundLegacy || leases.size === 0)
|
|
551
|
+
return null;
|
|
552
|
+
return {
|
|
553
|
+
schema_version: 'coordination/v1',
|
|
554
|
+
leases: [...leases.values()].sort(compareLeases),
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
function bootstrapEventsFromState(cwd, state) {
|
|
558
|
+
if (state.leases.length === 0 || hasV2CoordinationEvents(cwd))
|
|
559
|
+
return;
|
|
560
|
+
for (const lease of state.leases.sort(compareLeases)) {
|
|
561
|
+
const assessment = createAssessment('allow', loadCoordinationConfig(cwd).policy_mode, 'bootstrapped_from_materialized_state', []);
|
|
562
|
+
appendEvent(cwd, {
|
|
563
|
+
schema_version: 'coordination-event/v2',
|
|
564
|
+
type: 'lease_bootstrapped',
|
|
565
|
+
timestamp: lease.updated_at,
|
|
566
|
+
session_id: lease.session_id,
|
|
567
|
+
actor: lease.actor,
|
|
568
|
+
lease,
|
|
569
|
+
assessment,
|
|
570
|
+
overridden: Boolean(lease.force_overridden),
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
function hasV2CoordinationEvents(cwd) {
|
|
575
|
+
const path = join(cwd, EVENTS_PATH);
|
|
576
|
+
if (!existsSync(path))
|
|
577
|
+
return false;
|
|
578
|
+
try {
|
|
579
|
+
return readFileSync(path, 'utf-8')
|
|
580
|
+
.split('\n')
|
|
581
|
+
.map((line) => line.trim())
|
|
582
|
+
.filter(Boolean)
|
|
583
|
+
.some((line) => {
|
|
584
|
+
try {
|
|
585
|
+
const parsed = JSON.parse(line);
|
|
586
|
+
return parsed.schema_version === 'coordination-event/v2';
|
|
587
|
+
}
|
|
588
|
+
catch {
|
|
589
|
+
return false;
|
|
590
|
+
}
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
catch {
|
|
594
|
+
return false;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
function saveState(cwd, state) {
|
|
598
|
+
const path = join(cwd, LEASES_PATH);
|
|
599
|
+
ensureParent(path);
|
|
600
|
+
const tmp = `${path}.tmp`;
|
|
601
|
+
writeFileSync(tmp, JSON.stringify(state, null, 2) + '\n', 'utf-8');
|
|
602
|
+
renameSync(tmp, path);
|
|
603
|
+
}
|
|
604
|
+
function ensureParent(path) {
|
|
605
|
+
const dir = dirname(path);
|
|
606
|
+
if (!existsSync(dir))
|
|
607
|
+
mkdirSync(dir, { recursive: true });
|
|
608
|
+
}
|
|
609
|
+
function acquireLock(cwd) {
|
|
610
|
+
const lockPath = join(cwd, `${LEASES_PATH}.lock`);
|
|
611
|
+
ensureParent(lockPath);
|
|
612
|
+
const deadline = Date.now() + LOCK_TIMEOUT_MS;
|
|
613
|
+
while (Date.now() < deadline) {
|
|
614
|
+
try {
|
|
615
|
+
const fd = openSync(lockPath, 'wx');
|
|
616
|
+
closeSync(fd);
|
|
617
|
+
return () => {
|
|
618
|
+
try {
|
|
619
|
+
unlinkSync(lockPath);
|
|
620
|
+
}
|
|
621
|
+
catch { /* best effort */ }
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
catch {
|
|
625
|
+
const waitMs = Math.min(LOCK_RETRY_MS, deadline - Date.now());
|
|
626
|
+
if (waitMs <= 0)
|
|
627
|
+
break;
|
|
628
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, waitMs);
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
try {
|
|
632
|
+
unlinkSync(lockPath);
|
|
633
|
+
}
|
|
634
|
+
catch { /* ignore */ }
|
|
635
|
+
const fd = openSync(lockPath, 'wx');
|
|
636
|
+
closeSync(fd);
|
|
637
|
+
return () => {
|
|
638
|
+
try {
|
|
639
|
+
unlinkSync(lockPath);
|
|
640
|
+
}
|
|
641
|
+
catch { /* best effort */ }
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
function buildScopes(cwd, rawPaths) {
|
|
645
|
+
const repoIndex = loadRepoIndex(cwd);
|
|
646
|
+
const scopes = rawPaths.map((rawPath) => {
|
|
647
|
+
const normalized = normalizeRepoPath(cwd, rawPath);
|
|
648
|
+
return {
|
|
649
|
+
kind: detectScopeKind(cwd, rawPath),
|
|
650
|
+
path: normalized,
|
|
651
|
+
surface_key: deriveSurfaceKey(normalized),
|
|
652
|
+
ownership_keys: deriveOwnershipKeys(normalized, repoIndex),
|
|
653
|
+
};
|
|
654
|
+
});
|
|
655
|
+
return dedupeScopes(scopes);
|
|
656
|
+
}
|
|
657
|
+
function normalizeRepoPath(cwd, rawPath) {
|
|
658
|
+
const trimmed = rawPath.trim().replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '');
|
|
659
|
+
if (!trimmed)
|
|
660
|
+
return trimmed;
|
|
661
|
+
const absolute = resolve(cwd, trimmed);
|
|
662
|
+
const relativePath = relative(cwd, absolute).replace(/\\/g, '/');
|
|
663
|
+
return relativePath === '' ? trimmed : relativePath;
|
|
664
|
+
}
|
|
665
|
+
function detectScopeKind(cwd, rawPath) {
|
|
666
|
+
if (rawPath.endsWith('/'))
|
|
667
|
+
return 'directory';
|
|
668
|
+
const absolute = resolve(cwd, rawPath);
|
|
669
|
+
try {
|
|
670
|
+
return existsSync(absolute) && statSync(absolute).isDirectory() ? 'directory' : 'file';
|
|
671
|
+
}
|
|
672
|
+
catch {
|
|
673
|
+
return rawPath.includes('.') ? 'file' : 'directory';
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
function deriveSurfaceKey(path) {
|
|
677
|
+
const parts = path.split('/').filter(Boolean);
|
|
678
|
+
if (parts.length === 0)
|
|
679
|
+
return 'repo_root';
|
|
680
|
+
if ((parts[0] === 'packages' || parts[0] === 'services' || parts[0] === 'apps') && parts[1]) {
|
|
681
|
+
return `${parts[0]}/${parts[1]}`;
|
|
682
|
+
}
|
|
683
|
+
if (parts[0] === 'src' && parts[1]) {
|
|
684
|
+
return `${parts[0]}/${parts[1]}`;
|
|
685
|
+
}
|
|
686
|
+
return parts.slice(0, Math.min(2, parts.length)).join('/');
|
|
687
|
+
}
|
|
688
|
+
function deriveOwnershipKeys(path, repoIndex) {
|
|
689
|
+
const normalized = path.replace(/\\/g, '/');
|
|
690
|
+
const parts = normalized.split('/').filter(Boolean).map((part) => part.toLowerCase());
|
|
691
|
+
if (parts.length === 0)
|
|
692
|
+
return ['repo_root'];
|
|
693
|
+
const keys = new Set();
|
|
694
|
+
const primary = deriveSurfaceKey(normalized);
|
|
695
|
+
keys.add(`surface:${primary}`);
|
|
696
|
+
keys.add(primary);
|
|
697
|
+
if ((parts[0] === 'packages' || parts[0] === 'services' || parts[0] === 'apps' || parts[0] === 'src') && parts[1]) {
|
|
698
|
+
keys.add(`unit:${parts[0]}/${parts[1]}`);
|
|
699
|
+
}
|
|
700
|
+
for (const part of parts.slice(0, 6)) {
|
|
701
|
+
if (OWNERSHIP_TERMS.includes(part)) {
|
|
702
|
+
keys.add(`domain:${part}`);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
if (repoIndex) {
|
|
706
|
+
for (const linkedKey of deriveRepoIndexOwnershipKeys(normalized, repoIndex)) {
|
|
707
|
+
keys.add(linkedKey);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
return [...keys].sort((a, b) => a.localeCompare(b));
|
|
711
|
+
}
|
|
712
|
+
function deriveRepoIndexOwnershipKeys(path, repoIndex) {
|
|
713
|
+
const keys = new Set();
|
|
714
|
+
const directImports = repoIndex.dep_graph.imports[path] ?? [];
|
|
715
|
+
const directDependents = repoIndex.dep_graph.dependents[path] ?? [];
|
|
716
|
+
for (const neighbor of [...new Set([...directImports, ...directDependents])].sort((a, b) => a.localeCompare(b)).slice(0, 8)) {
|
|
717
|
+
const pair = [path, neighbor].sort((a, b) => a.localeCompare(b)).join('<->');
|
|
718
|
+
keys.add(`dep_link:${pair}`);
|
|
719
|
+
keys.add(`dep_unit:${deriveSurfaceKey(neighbor)}`);
|
|
720
|
+
if (isBoundedSharedNeighbor(neighbor, repoIndex)) {
|
|
721
|
+
keys.add(`shared_neighbor:${neighbor}`);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
for (const mapping of repoIndex.test_map) {
|
|
725
|
+
if (mapping.source_file === path || mapping.test_file === path) {
|
|
726
|
+
const other = mapping.source_file === path ? mapping.test_file : mapping.source_file;
|
|
727
|
+
const pair = [mapping.source_file, mapping.test_file].sort((a, b) => a.localeCompare(b)).join('<->');
|
|
728
|
+
keys.add(`test_link:${pair}`);
|
|
729
|
+
keys.add(`test_unit:${deriveSurfaceKey(other)}`);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
return [...keys].sort((a, b) => ownershipKeyRank(a) - ownershipKeyRank(b) || a.localeCompare(b));
|
|
733
|
+
}
|
|
734
|
+
function isBoundedSharedNeighbor(path, repoIndex) {
|
|
735
|
+
const fileName = path.split('/').at(-1)?.toLowerCase() ?? '';
|
|
736
|
+
if (GENERIC_OWNERSHIP_FILES.has(fileName))
|
|
737
|
+
return false;
|
|
738
|
+
const imports = repoIndex.dep_graph.imports[path] ?? [];
|
|
739
|
+
const dependents = repoIndex.dep_graph.dependents[path] ?? [];
|
|
740
|
+
return imports.length + dependents.length <= MAX_SHARED_NEIGHBOR_DEGREE;
|
|
741
|
+
}
|
|
742
|
+
function dedupeScopes(scopes) {
|
|
743
|
+
const seen = new Set();
|
|
744
|
+
return scopes.filter((scope) => {
|
|
745
|
+
const key = `${scope.kind}:${scope.path}:${scope.surface_key}:${(scope.ownership_keys ?? []).join('|')}`;
|
|
746
|
+
if (seen.has(key))
|
|
747
|
+
return false;
|
|
748
|
+
seen.add(key);
|
|
749
|
+
return true;
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
function assessLeaseRequest(requested, leases, policyMode) {
|
|
753
|
+
if (policyMode === 'off') {
|
|
754
|
+
return createAssessment('allow', policyMode, 'coordination_policy_off', []);
|
|
755
|
+
}
|
|
756
|
+
const overlaps = leases
|
|
757
|
+
.filter((lease) => lease.id !== requested.id && lease.session_id !== requested.session_id && lease.status === 'active')
|
|
758
|
+
.flatMap((lease) => buildOverlapRecords(requested.scopes, lease));
|
|
759
|
+
if (overlaps.length === 0) {
|
|
760
|
+
return createAssessment('allow', policyMode, 'no_overlaps_detected', []);
|
|
761
|
+
}
|
|
762
|
+
const decision = evaluatePolicyDecision(policyMode, requested.mode, overlaps);
|
|
763
|
+
return createAssessment(decision, policyMode, decision === 'block'
|
|
764
|
+
? policyMode === 'block-on-exact'
|
|
765
|
+
? 'blocked_exact_overlap'
|
|
766
|
+
: policyMode === 'block-on-surface'
|
|
767
|
+
? 'blocked_surface_overlap'
|
|
768
|
+
: 'blocked_single_writer_surface'
|
|
769
|
+
: 'overlap_detected_warn_only', sortOverlaps(overlaps));
|
|
770
|
+
}
|
|
771
|
+
function buildOverlapRecords(requestedScopes, lease) {
|
|
772
|
+
const overlaps = hasAnyOverlap(requestedScopes, lease.scopes);
|
|
773
|
+
if (overlaps.length === 0)
|
|
774
|
+
return [];
|
|
775
|
+
return overlaps.map((overlap) => ({
|
|
776
|
+
other_claim_id: lease.id,
|
|
777
|
+
other_session_id: lease.session_id,
|
|
778
|
+
other_actor: lease.actor,
|
|
779
|
+
other_mode: lease.mode,
|
|
780
|
+
other_status: lease.status,
|
|
781
|
+
kind: overlap.kind,
|
|
782
|
+
overlap_type: overlap.kind,
|
|
783
|
+
matched_scope: overlap.matched_scope,
|
|
784
|
+
surface_key: overlap.surface_key,
|
|
785
|
+
paths: overlap.paths,
|
|
786
|
+
surface_keys: overlap.surface_keys,
|
|
787
|
+
}));
|
|
788
|
+
}
|
|
789
|
+
function hasAnyOverlap(requestedScopes, existingScopes) {
|
|
790
|
+
const results = [];
|
|
791
|
+
for (const requested of requestedScopes) {
|
|
792
|
+
for (const existing of existingScopes) {
|
|
793
|
+
const overlap = detectOverlap(requested, existing);
|
|
794
|
+
if (overlap)
|
|
795
|
+
results.push(overlap);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
return dedupeOverlapPayloads(results);
|
|
799
|
+
}
|
|
800
|
+
function detectOverlap(requested, existing) {
|
|
801
|
+
if (requested.kind === 'file' && existing.kind === 'file' && requested.path === existing.path) {
|
|
802
|
+
return {
|
|
803
|
+
kind: 'exact_file',
|
|
804
|
+
matched_scope: requested.path,
|
|
805
|
+
surface_key: requested.surface_key,
|
|
806
|
+
paths: [requested.path],
|
|
807
|
+
surface_keys: [requested.surface_key],
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
if (requested.kind === 'directory' && (existing.path === requested.path || existing.path.startsWith(`${requested.path}/`))
|
|
811
|
+
|| existing.kind === 'directory' && (requested.path === existing.path || requested.path.startsWith(`${existing.path}/`))) {
|
|
812
|
+
return {
|
|
813
|
+
kind: 'directory_overlap',
|
|
814
|
+
matched_scope: requested.kind === 'directory' ? requested.path : existing.path,
|
|
815
|
+
surface_key: requested.surface_key === existing.surface_key ? requested.surface_key : findSharedOwnershipKey(requested, existing),
|
|
816
|
+
paths: [requested.path, existing.path].sort(),
|
|
817
|
+
surface_keys: [requested.surface_key, existing.surface_key].sort(),
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
const sharedOwnershipKey = findSharedOwnershipKey(requested, existing);
|
|
821
|
+
if (sharedOwnershipKey) {
|
|
822
|
+
return {
|
|
823
|
+
kind: 'surface_overlap',
|
|
824
|
+
matched_scope: sharedOwnershipKey.startsWith('domain:') ? sharedOwnershipKey : requested.path,
|
|
825
|
+
surface_key: sharedOwnershipKey,
|
|
826
|
+
paths: [requested.path, existing.path].sort(),
|
|
827
|
+
surface_keys: [sharedOwnershipKey],
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
return null;
|
|
831
|
+
}
|
|
832
|
+
function findSharedOwnershipKey(requested, existing) {
|
|
833
|
+
const requestedKeys = new Set(requested.ownership_keys ?? [requested.surface_key]);
|
|
834
|
+
const existingKeys = new Set(existing.ownership_keys ?? [existing.surface_key]);
|
|
835
|
+
const shared = [...requestedKeys]
|
|
836
|
+
.filter((key) => existingKeys.has(key))
|
|
837
|
+
.sort((a, b) => ownershipKeyRank(a) - ownershipKeyRank(b) || a.localeCompare(b));
|
|
838
|
+
return shared[0] ?? null;
|
|
839
|
+
}
|
|
840
|
+
function ownershipKeyRank(key) {
|
|
841
|
+
if (key.startsWith('surface:'))
|
|
842
|
+
return 0;
|
|
843
|
+
if (key.startsWith('unit:'))
|
|
844
|
+
return 1;
|
|
845
|
+
if (key.startsWith('dep_link:') || key.startsWith('test_link:'))
|
|
846
|
+
return 2;
|
|
847
|
+
if (key.startsWith('shared_neighbor:'))
|
|
848
|
+
return 3;
|
|
849
|
+
if (key.startsWith('dep_unit:') || key.startsWith('test_unit:'))
|
|
850
|
+
return 4;
|
|
851
|
+
if (key.startsWith('domain:'))
|
|
852
|
+
return 5;
|
|
853
|
+
return 6;
|
|
854
|
+
}
|
|
855
|
+
function evaluatePolicyDecision(policyMode, requestedMode, overlaps) {
|
|
856
|
+
if (policyMode === 'warn')
|
|
857
|
+
return 'warn';
|
|
858
|
+
if (policyMode === 'block-on-exact') {
|
|
859
|
+
return overlaps.some((overlap) => overlap.kind === 'exact_file') ? 'block' : 'warn';
|
|
860
|
+
}
|
|
861
|
+
if (policyMode === 'block-on-surface') {
|
|
862
|
+
const blocking = overlaps.some((overlap) => overlap.kind === 'exact_file' || overlap.kind === 'directory_overlap' || overlap.kind === 'surface_overlap');
|
|
863
|
+
if (!blocking)
|
|
864
|
+
return 'allow';
|
|
865
|
+
const allShared = requestedMode === 'shared' && overlaps.every((overlap) => overlap.other_mode === 'shared');
|
|
866
|
+
return allShared ? 'warn' : 'block';
|
|
867
|
+
}
|
|
868
|
+
if (policyMode === 'single-writer-per-surface') {
|
|
869
|
+
return overlaps.length > 0 ? 'block' : 'allow';
|
|
870
|
+
}
|
|
871
|
+
return 'allow';
|
|
872
|
+
}
|
|
873
|
+
function sortOverlaps(overlaps) {
|
|
874
|
+
const rank = {
|
|
875
|
+
exact_file: 0,
|
|
876
|
+
directory_overlap: 1,
|
|
877
|
+
surface_overlap: 2,
|
|
878
|
+
};
|
|
879
|
+
return [...overlaps].sort((a, b) => rank[a.kind] - rank[b.kind]
|
|
880
|
+
|| a.other_session_id.localeCompare(b.other_session_id)
|
|
881
|
+
|| a.paths.join(',').localeCompare(b.paths.join(',')));
|
|
882
|
+
}
|
|
883
|
+
function dedupeOverlapPayloads(overlaps) {
|
|
884
|
+
const seen = new Set();
|
|
885
|
+
return overlaps.filter((overlap) => {
|
|
886
|
+
const key = `${overlap.kind}:${overlap.matched_scope}:${overlap.surface_key ?? 'none'}:${overlap.paths.join('|')}:${overlap.surface_keys.join('|')}`;
|
|
887
|
+
if (seen.has(key))
|
|
888
|
+
return false;
|
|
889
|
+
seen.add(key);
|
|
890
|
+
return true;
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
function createAssessment(decision, policyMode, reason, overlaps) {
|
|
894
|
+
const exactOverlapCount = overlaps.filter((overlap) => overlap.kind === 'exact_file').length;
|
|
895
|
+
const surfaceOverlapCount = overlaps.length - exactOverlapCount;
|
|
896
|
+
const conflictingClaimIds = uniqueStrings(overlaps.map((overlap) => overlap.other_claim_id));
|
|
897
|
+
const conflictingSessionIds = uniqueStrings(overlaps.map((overlap) => overlap.other_session_id));
|
|
898
|
+
return {
|
|
899
|
+
decision,
|
|
900
|
+
policy_decision: decision,
|
|
901
|
+
policy_mode: policyMode,
|
|
902
|
+
reason,
|
|
903
|
+
exact_overlap_count: exactOverlapCount,
|
|
904
|
+
surface_overlap_count: surfaceOverlapCount,
|
|
905
|
+
conflicting_claim_ids: conflictingClaimIds,
|
|
906
|
+
conflicting_session_ids: conflictingSessionIds,
|
|
907
|
+
overlaps,
|
|
908
|
+
};
|
|
909
|
+
}
|
|
910
|
+
function uniqueStrings(values) {
|
|
911
|
+
return [...new Set(values)].sort((a, b) => a.localeCompare(b));
|
|
912
|
+
}
|
|
913
|
+
function refreshLeaseStatuses(leases, sessions, config, now) {
|
|
914
|
+
const transitions = [];
|
|
915
|
+
const heartbeats = [];
|
|
916
|
+
const staleCutoff = now.getTime() - config.stale_session_after_seconds * 1000;
|
|
917
|
+
for (const lease of leases) {
|
|
918
|
+
if (lease.status === 'released')
|
|
919
|
+
continue;
|
|
920
|
+
const previousStatus = lease.status;
|
|
921
|
+
let nextStatus = previousStatus;
|
|
922
|
+
let reason = lease.status_reason ?? 'lease_claimed';
|
|
923
|
+
const expiresAt = new Date(lease.expires_at).getTime();
|
|
924
|
+
if (expiresAt <= now.getTime()) {
|
|
925
|
+
nextStatus = 'expired';
|
|
926
|
+
reason = 'lease_ttl_expired';
|
|
927
|
+
}
|
|
928
|
+
else {
|
|
929
|
+
const session = sessions.get(lease.session_id);
|
|
930
|
+
if (!session) {
|
|
931
|
+
nextStatus = 'stale';
|
|
932
|
+
reason = 'session_missing';
|
|
933
|
+
}
|
|
934
|
+
else {
|
|
935
|
+
const sessionLastActive = new Date(session.last_active_at).getTime();
|
|
936
|
+
nextStatus = sessionLastActive < staleCutoff ? 'stale' : 'active';
|
|
937
|
+
reason = nextStatus === 'stale' ? 'session_inactive' : 'session_active';
|
|
938
|
+
const lastHeartbeat = new Date(lease.last_heartbeat_at).getTime();
|
|
939
|
+
if (nextStatus === 'active' && Number.isFinite(sessionLastActive) && sessionLastActive > lastHeartbeat) {
|
|
940
|
+
lease.last_heartbeat_at = now.toISOString();
|
|
941
|
+
lease.updated_at = now.toISOString();
|
|
942
|
+
lease.expires_at = new Date(now.getTime() + Math.max(lease.ttl_seconds, config.heartbeat_extension_seconds) * 1000).toISOString();
|
|
943
|
+
lease.status_reason = 'session_registry_heartbeat';
|
|
944
|
+
heartbeats.push({ ...lease });
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
if (nextStatus === previousStatus)
|
|
949
|
+
continue;
|
|
950
|
+
lease.status = nextStatus;
|
|
951
|
+
lease.status_reason = reason;
|
|
952
|
+
lease.updated_at = now.toISOString();
|
|
953
|
+
lease.last_status_change_at = now.toISOString();
|
|
954
|
+
transitions.push({
|
|
955
|
+
lease_id: lease.id,
|
|
956
|
+
from_status: previousStatus,
|
|
957
|
+
to_status: nextStatus,
|
|
958
|
+
reason,
|
|
959
|
+
lease: { ...lease },
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
return { transitions, heartbeats };
|
|
963
|
+
}
|
|
964
|
+
function touchSessionLeases(leases, sessionId, heartbeatExtensionSeconds, now, reason) {
|
|
965
|
+
const touched = [];
|
|
966
|
+
for (const lease of leases) {
|
|
967
|
+
if (lease.session_id !== sessionId || lease.status === 'released')
|
|
968
|
+
continue;
|
|
969
|
+
const previousStatus = lease.status;
|
|
970
|
+
lease.last_heartbeat_at = now.toISOString();
|
|
971
|
+
lease.updated_at = now.toISOString();
|
|
972
|
+
lease.expires_at = new Date(now.getTime() + Math.max(lease.ttl_seconds, heartbeatExtensionSeconds) * 1000).toISOString();
|
|
973
|
+
lease.status = 'active';
|
|
974
|
+
lease.status_reason = reason;
|
|
975
|
+
if (previousStatus !== 'active') {
|
|
976
|
+
lease.last_status_change_at = now.toISOString();
|
|
977
|
+
}
|
|
978
|
+
touched.push({ ...lease });
|
|
979
|
+
}
|
|
980
|
+
return touched;
|
|
981
|
+
}
|
|
982
|
+
function compareLeases(a, b) {
|
|
983
|
+
const rank = {
|
|
984
|
+
active: 0,
|
|
985
|
+
stale: 1,
|
|
986
|
+
expired: 2,
|
|
987
|
+
released: 3,
|
|
988
|
+
};
|
|
989
|
+
return rank[a.status] - rank[b.status]
|
|
990
|
+
|| a.session_id.localeCompare(b.session_id)
|
|
991
|
+
|| a.id.localeCompare(b.id);
|
|
992
|
+
}
|
|
993
|
+
function appendTransitionEvents(cwd, transitions, now) {
|
|
994
|
+
for (const transition of transitions) {
|
|
995
|
+
appendEvent(cwd, {
|
|
996
|
+
schema_version: 'coordination-event/v2',
|
|
997
|
+
type: 'lease_status_changed',
|
|
998
|
+
timestamp: now.toISOString(),
|
|
999
|
+
session_id: transition.lease.session_id,
|
|
1000
|
+
actor: transition.lease.actor,
|
|
1001
|
+
lease: transition.lease,
|
|
1002
|
+
reason: transition.reason,
|
|
1003
|
+
from_status: transition.from_status,
|
|
1004
|
+
to_status: transition.to_status,
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
function appendHeartbeatEvents(cwd, leases, now, reason) {
|
|
1009
|
+
for (const lease of leases) {
|
|
1010
|
+
appendEvent(cwd, {
|
|
1011
|
+
schema_version: 'coordination-event/v2',
|
|
1012
|
+
type: 'lease_heartbeat',
|
|
1013
|
+
timestamp: now.toISOString(),
|
|
1014
|
+
session_id: lease.session_id,
|
|
1015
|
+
actor: lease.actor,
|
|
1016
|
+
lease,
|
|
1017
|
+
reason,
|
|
1018
|
+
});
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
function appendEvent(cwd, event) {
|
|
1022
|
+
const path = join(cwd, EVENTS_PATH);
|
|
1023
|
+
ensureParent(path);
|
|
1024
|
+
appendFileSync(path, JSON.stringify(event) + '\n', 'utf-8');
|
|
1025
|
+
}
|
|
1026
|
+
function appendValidation(cwd, record) {
|
|
1027
|
+
const path = join(cwd, VALIDATIONS_PATH);
|
|
1028
|
+
ensureParent(path);
|
|
1029
|
+
appendFileSync(path, JSON.stringify(record) + '\n', 'utf-8');
|
|
1030
|
+
}
|
|
1031
|
+
function appendTimelineDecision(cwd, sessionId, subject, payload) {
|
|
1032
|
+
if (!sessionId)
|
|
1033
|
+
return;
|
|
1034
|
+
appendDecisionEvent(cwd, sessionId, newTimelineCommandId('coord'), subject, JSON.stringify(payload), 'OBSERVED');
|
|
1035
|
+
}
|
|
1036
|
+
function gitOutput(cwd, command) {
|
|
1037
|
+
try {
|
|
1038
|
+
return execSync(command, { cwd, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 5000 }).trim() || null;
|
|
1039
|
+
}
|
|
1040
|
+
catch {
|
|
1041
|
+
return null;
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
function loadRepoIndex(cwd) {
|
|
1045
|
+
const configPath = join(cwd, '.codeledger', 'config.json');
|
|
1046
|
+
const fallbackPath = join(cwd, '.codeledger', 'cache', 'repo-index.json');
|
|
1047
|
+
let repoIndexPath = fallbackPath;
|
|
1048
|
+
if (existsSync(configPath)) {
|
|
1049
|
+
try {
|
|
1050
|
+
const parsed = JSON.parse(readFileSync(configPath, 'utf-8'));
|
|
1051
|
+
if (parsed.workspace?.cache_dir) {
|
|
1052
|
+
repoIndexPath = join(cwd, parsed.workspace.cache_dir, 'repo-index.json');
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
catch {
|
|
1056
|
+
repoIndexPath = fallbackPath;
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
if (!existsSync(repoIndexPath))
|
|
1060
|
+
return null;
|
|
1061
|
+
try {
|
|
1062
|
+
return JSON.parse(readFileSync(repoIndexPath, 'utf-8'));
|
|
1063
|
+
}
|
|
1064
|
+
catch {
|
|
1065
|
+
return null;
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
function loadSessionLookup(cwd) {
|
|
1069
|
+
const path = join(cwd, '.codeledger', 'sessions', 'registry.json');
|
|
1070
|
+
if (!existsSync(path))
|
|
1071
|
+
return new Map();
|
|
1072
|
+
try {
|
|
1073
|
+
const parsed = JSON.parse(readFileSync(path, 'utf-8'));
|
|
1074
|
+
return new Map((parsed.sessions ?? []).map((session) => [session.session_id, session]));
|
|
1075
|
+
}
|
|
1076
|
+
catch {
|
|
1077
|
+
return new Map();
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
function collectAllHotOverlaps(leases) {
|
|
1081
|
+
const results = [];
|
|
1082
|
+
for (let index = 0; index < leases.length; index += 1) {
|
|
1083
|
+
const current = leases[index];
|
|
1084
|
+
for (let otherIndex = index + 1; otherIndex < leases.length; otherIndex += 1) {
|
|
1085
|
+
const other = leases[otherIndex];
|
|
1086
|
+
if (current.session_id === other.session_id)
|
|
1087
|
+
continue;
|
|
1088
|
+
results.push(...buildOverlapRecords(current.scopes, other));
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
return sortOverlaps(results);
|
|
1092
|
+
}
|
|
1093
|
+
//# sourceMappingURL=index.js.map
|