Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions scripts/hooks/session-end-marker.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

const {
resolveProjectContext,
getAliasContexts,
removeSessionLease,
listSessionLeases,
stopObserverForContext,
Expand All @@ -30,17 +31,21 @@ function run(rawInput) {

try {
const observerContext = resolveProjectContext();
removeSessionLease(observerContext, sessionId);
const remainingLeases = listSessionLeases(observerContext);
// Leases from sessions that started before a remote was added sit under the root's older ids.
const contexts = [observerContext, ...getAliasContexts(observerContext)];
for (const context of contexts) removeSessionLease(context, sessionId);
const remainingLeases = contexts.reduce((count, context) => count + listSessionLeases(context).length, 0);

if (remainingLeases.length === 0) {
if (stopObserverForContext(observerContext)) {
log(`Stopped observer for project ${observerContext.projectId} after final session lease ended`);
} else {
log(`No running observer to stop for project ${observerContext.projectId}`);
if (remainingLeases === 0) {
for (const context of contexts) {
Comment on lines +37 to +40

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Old observer stays running

When checkout A starts under a path-based ID, gains a remote, and checkout B uses that same remote, this combined lease count retains both observers when A ends because B still has a lease. When B ends, its root-scoped alias list excludes A’s old ID, so it stops only the remote-ID observer. The old observer remains running with no leases after both sessions have ended and must wait for its separate idle cleanup, whose default timeout is 30 minutes.

This is a non-blocking process-cleanup gap. Stop each context’s observer when its own leases are exhausted, or retain enough alias information for the final session to clean up every deferred observer. Add a two-checkout regression test.

Artifacts

Complete executed regression script

  • Uploaded the unchanged full source of the executed real-hook regression harness; the upload returned HTTP 200.

Complete executed evidence capture script

  • Uploaded the unchanged full source of the executed capture runner; the upload returned HTTP 200.

Parent lifecycle with both observers stopped

  • Uploaded the existing parent execution log showing both observers stopped after both sessions ended; the upload returned HTTP 200.

HEAD lifecycle with old observer still running

  • Uploaded the existing HEAD execution log showing the old observer alive after both sessions ended; the upload returned HTTP 200.

Scoped observer test results

  • Uploaded the existing output showing 14 library cases and 10 lifecycle cases passing; the upload returned HTTP 200.

Source citations and complete executed script content

  • Uploaded the existing captured source record containing numbered citations, revision IDs, hashes, and both complete executed scripts; the upload returned HTTP 200.

View artifacts

TREX Ran code and verified through TREX

Prompt To Fix With AI
This is a comment left during a code review.
Path: scripts/hooks/session-end-marker.js
Line: 37-40

Comment:
**Old observer stays running**

When checkout A starts under a path-based ID, gains a remote, and checkout B uses that same remote, this combined lease count retains both observers when A ends because B still has a lease. When B ends, its root-scoped alias list excludes A’s old ID, so it stops only the remote-ID observer. The old observer remains running with no leases after both sessions have ended and must wait for its separate idle cleanup, whose default timeout is 30 minutes.

This is a non-blocking process-cleanup gap. Stop each context’s observer when its own leases are exhausted, or retain enough alias information for the final session to clean up every deferred observer. Add a two-checkout regression test.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

if (stopObserverForContext(context)) {
log(`Stopped observer for project ${context.projectId} after final session lease ended`);
} else if (context === observerContext) {
log(`No running observer to stop for project ${context.projectId}`);
}
}
} else {
log(`Retained observer for project ${observerContext.projectId}; ${remainingLeases.length} session lease(s) remain`);
log(`Retained observer for project ${observerContext.projectId}; ${remainingLeases} session lease(s) remain`);
}
} catch (err) {
log(`Observer cleanup skipped: ${err.message}`);
Expand Down
83 changes: 79 additions & 4 deletions scripts/lib/observer-sessions.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,68 @@ function resolveProjectRoot(cwd = process.cwd()) {
return '';
}

function resolveMainWorktreeRoot(projectRoot) {
const listing = runGit(['worktree', 'list', '--porcelain'], projectRoot);
const line = listing.split(/\r?\n/).find(entry => entry.startsWith('worktree '));
return line ? line.slice('worktree '.length) : '';
}

function computeProjectId(projectRoot) {
const remoteUrl = stripRemoteCredentials(runGit(['remote', 'get-url', 'origin'], projectRoot));
const hashInput = normalizeRemoteUrl(remoteUrl) || remoteUrl || projectRoot;
// Same fallback as detect-project.sh: a remote-free linked worktree shares its main checkout's id.
const hashInput = normalizeRemoteUrl(remoteUrl) || remoteUrl || resolveMainWorktreeRoot(projectRoot) || projectRoot;
return crypto.createHash('sha256').update(hashInput).digest('hex').slice(0, 12);
}

// detect-project.sh creates instincts/ before it updates projects.json, so a
// folder with instincts/ is one the observer writes to (a bare folder may be
// one this module created).
function hasObserverData(projectId) {
return fs.existsSync(path.join(getProjectsDir(), projectId, 'instincts'));
}

// Match the project CLI's ID boundary before using registry data in paths.
function isSafeProjectId(projectId) {
return typeof projectId === 'string' && projectId.length <= 128
&& /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(projectId)
&& !projectId.includes('..');
}

/**
* Choose the project id for a root that has registry entries.
*
* After a repository gains a remote, detect-project.sh writes under the
* remote-hash id while the old path-hash entry stays in the registry. Prefer
* the id the observer derives now when it is registered or already holds
* observer data; otherwise keep a sole entry, or take the most recently seen
* of several. When other ids remain for the root, show a read-only inspection
* path. The current merge CLI deletes the source directory, including live
* observer state and files it does not copy, so SessionStart must not suggest it.
*/
function pickRootProjectId(entries, projectRoot) {
const computedId = computeProjectId(projectRoot);
const ids = [...new Set(entries.map(entry => entry.id))];
const lastSeen = entry => Date.parse(entry.last_seen || '') || 0;
let chosenId;
if (ids.includes(computedId) || hasObserverData(computedId)) {
chosenId = computedId;
} else if (entries.length === 1) {
return ids[0];
} else {
chosenId = entries.reduce((latest, entry) => (lastSeen(entry) > lastSeen(latest) ? entry : latest)).id;
}

const others = ids.filter(id => id !== chosenId);
if (others.length > 0) {
process.stderr.write(
`[ecc] ${projectRoot} has project ids ${[chosenId, ...others].join(', ')}; using ${chosenId}. `
+ 'Inspect with instinct-cli.py projects; do not merge live project storage. '
+ 'The merge command removes the source directory.\n'
);
}
return chosenId;
}

function resolveProjectContext(cwd = process.cwd()) {
const projectRoot = resolveProjectRoot(cwd);
if (!projectRoot) {
Expand All @@ -100,12 +156,30 @@ function resolveProjectContext(cwd = process.cwd()) {
}

const registry = readProjectRegistry();
const registryEntry = Object.values(registry).find(entry => entry && path.resolve(entry.root || '') === projectRoot);
const projectId = registryEntry?.id || computeProjectId(projectRoot);
const rootEntries = Object.values(registry).filter(entry => entry && isSafeProjectId(entry.id)
&& path.resolve(entry.root || '') === projectRoot);
const projectId = rootEntries.length > 0
? pickRootProjectId(rootEntries, projectRoot)
: computeProjectId(projectRoot);
const projectDir = path.join(getProjectsDir(), projectId);
ensureDir(projectDir);
const aliasProjectIds = [...new Set(rootEntries.map(entry => entry.id))].filter(id => id !== projectId);

return { projectId, projectRoot, projectDir, isGlobal: false, aliasProjectIds };
}

return { projectId, projectRoot, projectDir, isGlobal: false };
/**
* Contexts for the other registry ids that share this root. A remote added
* mid-session moves the root to a new id, so a SessionStart lease can still
* sit under one of these.
*/
function getAliasContexts(context) {
return [...new Set((context.aliasProjectIds || []).filter(isSafeProjectId))].map(projectId => ({
...context,
projectId,
projectDir: path.join(getProjectsDir(), projectId),
aliasProjectIds: []
}));
}

function getObserverPidFile(context) {
Expand Down Expand Up @@ -201,6 +275,7 @@ module.exports = {
getHomunculusDir,
normalizeRemoteUrl,
resolveProjectContext,
getAliasContexts,
getObserverActivityFile,
getObserverPidFile,
getSessionLeaseDir,
Expand Down
50 changes: 50 additions & 0 deletions tests/hooks/observer-session-lifecycle.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,56 @@ test('in-process SessionEnd stops the observer only after the final payload leas
}));
});

test('in-process SessionEnd releases a lease left under the root\'s older id after a remote was added mid-session', () => {
withFixture(fixture => withEnv(fixture.overrides, () => {
const store = fixture.overrides.CLV2_HOMUNCULUS_DIR;
fs.writeFileSync(path.join(store, 'projects.json'), JSON.stringify({
'fixture-project': { id: 'fixture-project', root: fixture.project, last_seen: '2026-10-19T00:00:00Z' },
'remote-project': { id: 'remote-project', root: fixture.project, last_seen: '2026-10-20T00:00:00Z' }
}));
seedLease(fixture, 'started-before-remote');
const stops = [];
const { run } = loadEndMarkerWithStubbedStop(stops);
const input = '{"session_id":"started-before-remote"}\n';
const originalWrite = process.stderr.write;
process.stderr.write = () => true;
try {
assert.strictEqual(run(input), input);
} finally {
process.stderr.write = originalWrite;
}
assert.ok(!fs.existsSync(leaseFile(fixture, 'started-before-remote')));
assert.deepStrictEqual(stops, ['remote-project', 'fixture-project']);
}));
});

test('in-process SessionEnd keeps observers running while another session still holds a lease under an older id', () => {
withFixture(fixture => withEnv(fixture.overrides, () => {
const store = fixture.overrides.CLV2_HOMUNCULUS_DIR;
fs.writeFileSync(path.join(store, 'projects.json'), JSON.stringify({
'fixture-project': { id: 'fixture-project', root: fixture.project, last_seen: '2026-10-19T00:00:00Z' },
'remote-project': { id: 'remote-project', root: fixture.project, last_seen: '2026-10-20T00:00:00Z' }
}));
seedLease(fixture, 'older-one');
seedLease(fixture, 'older-two');
const stops = [];
const { run } = loadEndMarkerWithStubbedStop(stops);
const originalWrite = process.stderr.write;
process.stderr.write = () => true;
try {
run('{"session_id":"older-one"}\n');
assert.ok(!fs.existsSync(leaseFile(fixture, 'older-one')));
assert.ok(fs.existsSync(leaseFile(fixture, 'older-two')));
assert.deepStrictEqual(stops, []);
run('{"session_id":"older-two"}\n');
} finally {
process.stderr.write = originalWrite;
}
assert.ok(!fs.existsSync(leaseFile(fixture, 'older-two')));
assert.deepStrictEqual(stops, ['remote-project', 'fixture-project']);
}));
});

for (const envKey of ['ECC_SESSION_ID', 'CLAUDE_SESSION_ID']) {
test(`both lifecycle hooks retain ${envKey} fallback for malformed stdin`, () => {
withFixture(fixture => {
Expand Down
Loading
Loading