feat(cli): Cursor emits AGENT_NOTIFY_SUMMARY when status-summary toggle is on (#2354)

* feat(cli): Cursor emits AGENT_NOTIFY_SUMMARY via rules overlay

When Emit status summaries is on, install a transient workspace
.cursor/rules overlay for Cursor ACP sessions and clean it up on
teardown, closing the flavor hole left after #1376.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): harden Cursor notify-rule overlay ownership and exclude

Address review on the emit overlay: clear ownership state under lock,
refresh crash-recovery snapshots after user replacement, fall back to
an alternate rule filename when the primary path is tracked, and lease
.git/info/exclude so git add -A cannot stage the transient rule.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): path-scope notify overlay ownership and reap excludes

Refresh restore snapshots on live user replacements, key ownership by
selected rule path, and prune dead PID-stamped .git/info/exclude leases
left by crashed Cursor sessions.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): harden Cursor notify overlay against symlink and path traps

Refuse rule writes through symlinks, canonicalize workspace paths for
ownership, escape literal Git exclude patterns, and qualify settings
copy as Cursor ACP.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): preserve unreadable rules and file modes in notify overlay

Skip install when an existing rule cannot be backed up, restore original
permission bits on cleanup, and stop retrying ownership-lock callback
failures as lock contention.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): keep notify overlay restore snapshot on unreadable cleanup

When teardown cannot read the generated rule, leave the file alone but
retain the private ownership snapshot so a later session can restore the
user's original content; write state.json as 0600.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): restore notify overlay snapshot even if install never wrote

Last-owner cleanup now restores from the shared snapshot whenever the
on-disk rule is still HAPI-owned, including handles that registered then
failed before writing the generated rule.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): write notify overlay ownership state atomically

Replace in-place state.json writes with temp+rename so a partial failure
cannot destroy the only backup of a user rule, and harden the failed-
install recovery test to actually chmod the exclude file.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): fail closed on abandoned notify overlay locks

Publish pid+token via link(2) like the MCP overlay so a crashed holder
leaves an identifiable lock, and surface an actionable rm path instead of
silently spinning for five seconds.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): retry notify overlay lock when holder already released

After link EEXIST, a missing lock means the contender freed it before our
owner read - retry acquire instead of misreporting the path as abandoned.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): treat notify lock ENOENT during owner read as retry

Distinguish missing vs invalid lock contents so a holder that releases
between existsSync and readFile is not misclassified as abandoned.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): recreate notify overlay stateDir under the ownership lock

Last-owner cleanup no longer rmdirs stateDir, and install mkdir+write runs
inside the lock so a waiting installer cannot hit ENOENT on state.json.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
HeavyGee
2026-11-10 15:12:06 +08:00
committed by GitHub
co-authored by Cursor
parent ce6d074a54
commit 39da0be557
9 changed files with 1657 additions and 11 deletions
@@ -44,6 +44,8 @@ const harness = vi.hoisted(() => ({
stderrErrorHandler: null as ((error: { type: string; message: string; raw?: string }) => void) | null,
disconnectError: null as Error | null,
overlayCleanup: null as ReturnType<typeof vi.fn> | null,
notifyRuleInstallCalls: [] as Array<{ cwd: string; project?: string | null; agentId?: string | null }>,
notifyRuleCleanup: null as ReturnType<typeof vi.fn> | null,
agentActivityListener: null as ((thinking: boolean, source?: string) => void) | null,
titleSyncControllers: [] as unknown[],
titleSyncRegistered: [] as unknown[],
@@ -285,6 +287,18 @@ vi.mock('./utils/cursorMcpOverlay', () => ({
},
}));
vi.mock('./utils/cursorNotifyRuleOverlay', () => ({
installCursorNotifyRuleOverlay: (opts: {
cwd: string
project?: string | null
agentId?: string | null
}) => {
harness.notifyRuleInstallCalls.push(opts);
harness.notifyRuleCleanup = vi.fn();
return { rulePath: `${opts.cwd}/.cursor/rules/hapi-session.mdc`, cleanup: harness.notifyRuleCleanup };
},
}));
vi.mock('@/ui/ink/OpencodeDisplay', () => ({
OpencodeDisplay: () => null
}));
@@ -298,6 +312,10 @@ import { createCursorAcpBackend } from './utils/cursorAcpBackend';
import { RPC_METHODS } from '@hapi/protocol/rpcMethods';
import { CursorSession } from './session';
import { ApiSessionClient } from '@/api/apiSession';
import {
applyHubSessionSummaryContract,
resetSessionSummaryContractForTests
} from '@/modules/common/sessionSummaryInstruction';
import {
_resetSharedCursorModelsCacheForTests,
writeSharedCursorModelsCache
@@ -394,7 +412,11 @@ describe('cursorAcpRemoteLauncher', () => {
harness.stderrErrorHandler = null;
harness.disconnectError = null;
harness.overlayCleanup = null;
harness.notifyRuleInstallCalls = [];
harness.notifyRuleCleanup = null;
harness.agentActivityListener = null;
resetSessionSummaryContractForTests();
delete process.env.HAPI_SESSION_SUMMARY_CONTRACT;
harness.titleSyncControllers = [];
harness.titleSyncRegistered = [];
harness.onChangeTitle = null;
@@ -412,6 +434,8 @@ describe('cursorAcpRemoteLauncher', () => {
afterEach(() => {
vi.clearAllMocks();
_resetSharedCursorModelsCacheForTests();
resetSessionSummaryContractForTests();
delete process.env.HAPI_SESSION_SUMMARY_CONTRACT;
});
it('ends the launcher when a soft steer outlives an abort', async () => {
@@ -1152,6 +1176,35 @@ describe('cursorAcpRemoteLauncher', () => {
expect(harness.overlayCleanup).toHaveBeenCalled();
});
it('installs the notify-rule overlay when emit status summaries is on', async () => {
applyHubSessionSummaryContract(true);
const session = makeSession(null);
await cursorAcpRemoteLauncher(session);
expect(harness.notifyRuleInstallCalls).toEqual([
{ cwd: '/tmp/project', project: 'project', agentId: 'test-session-id' }
]);
expect(harness.notifyRuleCleanup).toHaveBeenCalled();
});
it('skips the notify-rule overlay when emit status summaries is off', async () => {
applyHubSessionSummaryContract(false);
const session = makeSession(null);
await cursorAcpRemoteLauncher(session);
expect(harness.notifyRuleInstallCalls).toEqual([]);
expect(harness.notifyRuleCleanup).toBeNull();
});
it('removes the notify-rule overlay even when backend.disconnect rejects', async () => {
applyHubSessionSummaryContract(true);
harness.disconnectError = new Error('disconnect failed');
const session = makeSession(null);
await expect(cursorAcpRemoteLauncher(session)).rejects.toThrow('disconnect failed');
expect(harness.notifyRuleCleanup).toHaveBeenCalled();
});
it('drops post-done harness speech after the HAPI prompt ends (#2267)', async () => {
const doneFooter =
'AGENT_NOTIFY_SUMMARY {"version":1,"agent":"a","project":"hapi","status":"done","summary":"Topic closed"}';
+26 -2
View File
@@ -1,5 +1,6 @@
import React from 'react';
import { randomUUID } from 'node:crypto';
import { basename } from 'node:path';
import { logger } from '@/ui/logger';
import { AsyncLock } from '@/utils/lock';
import { buildHapiMcpBridge } from '@/codex/utils/buildHapiMcpBridge';
@@ -11,6 +12,7 @@ import {
type RemoteLauncherDisplayContext,
type RemoteLauncherExitReason
} from '@/modules/common/remote/RemoteLauncherBase';
import { isSessionSummaryContractEnabled } from '@/modules/common/sessionSummaryInstruction';
import { OpencodeDisplay } from '@/ui/ink/OpencodeDisplay';
import type { CursorSession } from './session';
import type { PermissionMode } from './loop';
@@ -44,6 +46,10 @@ import {
installCursorMcpOverlay,
type CursorMcpOverlayHandle,
} from './utils/cursorMcpOverlay';
import {
installCursorNotifyRuleOverlay,
type CursorNotifyRuleOverlay
} from './utils/cursorNotifyRuleOverlay';
import {
resolveCursorSpawnModel,
tryRemapCursorSpawnModelFromConnectError
@@ -97,6 +103,8 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase {
/** Avoid re-queueing `/auto-review` on every mid-session mode sync. */
private autoReviewSlashQueued = false;
private cursorMcpOverlay: CursorMcpOverlayHandle | null = null;
/** Transient workspace `.cursor/rules` overlay when emit status summaries is on. */
private notifyRuleOverlay: CursorNotifyRuleOverlay | null = null;
private pendingRetryableError: string | null = null;
private pendingRetryableFromStderr = false;
private pendingInlineRetryableError = false;
@@ -137,6 +145,18 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase {
});
this.happyServer = happyServer;
// Install the workspace session-summary rule before the backend spawns
// cursor-agent, so the `.cursor/rules` file is on disk when it reads
// workspace rules. Gated on the same emit setting as other flavors.
// Restored/removed in cleanup().
if (isSessionSummaryContractEnabled()) {
this.notifyRuleOverlay = installCursorNotifyRuleOverlay({
cwd: session.path,
project: basename(session.path) || null,
agentId: session.client.sessionId || null
});
}
const hapiBridge = mcpServers.hapi;
if (hapiBridge) {
try {
@@ -869,10 +889,13 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase {
}
protected async cleanup(): Promise<void> {
// Capture overlay before awaited teardown so a reject from
// cancelAll/disconnect cannot leave a dead hapi-* entry in ~/.cursor/mcp.json.
// Capture overlays before awaited teardown so a reject from
// cancelAll/disconnect cannot leave a dead hapi-* MCP entry or a
// leftover session-summary rule on disk.
const overlay = this.cursorMcpOverlay;
this.cursorMcpOverlay = null;
const notifyOverlay = this.notifyRuleOverlay;
this.notifyRuleOverlay = null;
this.sessionTeardownStarted = true;
try {
@@ -912,6 +935,7 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase {
}
} finally {
overlay?.cleanup();
notifyOverlay?.cleanup();
setCursorAcpModelsSnapshot(null);
}
}
@@ -0,0 +1,678 @@
import { execFileSync } from 'node:child_process';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
chmodSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
readdirSync,
rmSync,
statSync,
symlinkSync,
unlinkSync,
writeFileSync
} from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { SESSION_SUMMARY_CONTRACT_LINE } from '@/modules/common/sessionSummaryInstruction';
import {
buildNotifyRuleContent,
classifyContendedNotifyOverlayLock,
HAPI_NOTIFY_GIT_EXCLUDE_MARKER_PREFIX,
HAPI_SESSION_RULE_SENTINEL,
installCursorNotifyRuleOverlay,
readNotifyOverlayLockOwner,
RULE_FILENAME_ALTERNATE,
RULE_FILENAME_PRIMARY,
toLiteralGitExcludePattern,
withNotifyOverlayLock
} from './cursorNotifyRuleOverlay';
describe('buildNotifyRuleContent', () => {
it('includes alwaysApply frontmatter, sentinel, and the contract line', () => {
const content = buildNotifyRuleContent();
expect(content.startsWith('---\nalwaysApply: true\n---')).toBe(true);
expect(content).toContain(HAPI_SESSION_RULE_SENTINEL);
expect(content).toContain(SESSION_SUMMARY_CONTRACT_LINE);
expect(content).toContain('"status":"done|blocked|needs_review|needs_decision|failed|stalled"');
expect(content.toLowerCase()).toContain('omit the action key');
expect(content).toContain('Never emit "action":""');
expect(content).toContain('final answer only');
expect(content).toContain('After status "done", do not emit further user-visible replies');
expect(content).not.toContain('End every response');
});
it('bakes in project and agent id when provided', () => {
const content = buildNotifyRuleContent({ project: 'status-summary-emit', agentId: 'peer-7' });
expect(content).toContain('"agent":"peer-7"');
expect(content).toContain('"project":"status-summary-emit"');
});
it('falls back to placeholders and sanitizes hostile input', () => {
const content = buildNotifyRuleContent({ project: '"}{evil', agentId: ' ' });
expect(content).toContain('"agent":"<agent-id>"');
expect(content).toContain('"project":"evil"');
});
it('reads as benign session tracking, never surveillance', () => {
const content = buildNotifyRuleContent().toLowerCase();
expect(content).toContain('session tracking');
expect(content).not.toContain('overseer');
expect(content).not.toContain('surveillance');
expect(content).not.toContain('monitor');
});
});
describe('installCursorNotifyRuleOverlay', () => {
let cwd: string;
let hapiHome: string;
let previousHapiHome: string | undefined;
beforeEach(() => {
cwd = mkdtempSync(join(tmpdir(), 'hapi-notify-rule-'));
hapiHome = mkdtempSync(join(tmpdir(), 'hapi-home-'));
previousHapiHome = process.env.HAPI_HOME;
process.env.HAPI_HOME = hapiHome;
});
afterEach(() => {
rmSync(cwd, { recursive: true, force: true });
rmSync(hapiHome, { recursive: true, force: true });
if (previousHapiHome === undefined) {
delete process.env.HAPI_HOME;
} else {
process.env.HAPI_HOME = previousHapiHome;
}
});
const rulePathOf = (root: string) => join(root, '.cursor', 'rules', 'hapi-session.mdc');
it('keeps ownership state outside the workspace', () => {
mkdirSync(join(cwd, '.cursor', 'rules'), { recursive: true });
writeFileSync(rulePathOf(cwd), '# tracked\n', 'utf-8');
const overlay = installCursorNotifyRuleOverlay({ cwd });
expect(existsSync(join(cwd, '.cursor', 'rules', 'hapi-session.mdc.hapi-refs'))).toBe(false);
expect(existsSync(join(cwd, '.cursor', 'rules', 'hapi-session.mdc.hapi-restore'))).toBe(false);
expect(readdirSync(hapiHome).length).toBeGreaterThan(0);
overlay.cleanup();
});
it('writes the rule file and reports its path', () => {
const overlay = installCursorNotifyRuleOverlay({ cwd });
expect(overlay.rulePath).toBe(rulePathOf(cwd));
expect(existsSync(overlay.rulePath)).toBe(true);
expect(readFileSync(overlay.rulePath, 'utf-8')).toContain(HAPI_SESSION_RULE_SENTINEL);
});
it('cleanup removes our file and prunes dirs it created', () => {
const overlay = installCursorNotifyRuleOverlay({ cwd });
overlay.cleanup();
expect(existsSync(overlay.rulePath)).toBe(false);
expect(existsSync(join(cwd, '.cursor', 'rules'))).toBe(false);
expect(existsSync(join(cwd, '.cursor'))).toBe(false);
});
it('backs up and restores a pre-existing user rule verbatim', () => {
const rulePath = rulePathOf(cwd);
mkdirSync(join(cwd, '.cursor', 'rules'), { recursive: true });
const userContent = '---\nalwaysApply: false\n---\n# my own rule\n';
writeFileSync(rulePath, userContent, 'utf-8');
const overlay = installCursorNotifyRuleOverlay({ cwd });
expect(readFileSync(rulePath, 'utf-8')).toContain(HAPI_SESSION_RULE_SENTINEL);
overlay.cleanup();
expect(readFileSync(rulePath, 'utf-8')).toBe(userContent);
expect(existsSync(join(cwd, '.cursor', 'rules'))).toBe(true);
});
it('does not prune a .cursor dir that has other content', () => {
mkdirSync(join(cwd, '.cursor'), { recursive: true });
writeFileSync(join(cwd, '.cursor', 'mcp.json'), '{}', 'utf-8');
const overlay = installCursorNotifyRuleOverlay({ cwd });
overlay.cleanup();
expect(existsSync(overlay.rulePath)).toBe(false);
expect(existsSync(join(cwd, '.cursor', 'rules'))).toBe(false);
expect(existsSync(join(cwd, '.cursor'))).toBe(true);
expect(existsSync(join(cwd, '.cursor', 'mcp.json'))).toBe(true);
});
it('restores a pre-existing tracked/user file after overlay cleanup', () => {
const rulePath = rulePathOf(cwd);
mkdirSync(join(cwd, '.cursor', 'rules'), { recursive: true });
const prior = '# tracked repo rule\nalwaysApply: false\n';
writeFileSync(rulePath, prior, 'utf-8');
const overlay = installCursorNotifyRuleOverlay({ cwd, project: 'session' });
expect(readFileSync(rulePath, 'utf-8')).toContain('"project":"session"');
overlay.cleanup();
expect(readFileSync(rulePath, 'utf-8')).toBe(prior);
});
it('last concurrent cleanup restores the original, not the peer overlay', () => {
const rulePath = rulePathOf(cwd);
mkdirSync(join(cwd, '.cursor', 'rules'), { recursive: true });
const tracked = buildNotifyRuleContent({ project: 'tracked-repo', agentId: 'repo' });
writeFileSync(rulePath, tracked, 'utf-8');
const first = installCursorNotifyRuleOverlay({ cwd, project: 'older', agentId: 'a' });
const second = installCursorNotifyRuleOverlay({ cwd, project: 'newer', agentId: 'b' });
expect(readFileSync(rulePath, 'utf-8')).toContain('"project":"newer"');
first.cleanup();
expect(readFileSync(rulePath, 'utf-8')).toContain('"project":"newer"');
second.cleanup();
expect(readFileSync(rulePath, 'utf-8')).toBe(tracked);
});
it('deletes generated rule after crash recovery when no prior file existed', () => {
const rulePath = rulePathOf(cwd);
installCursorNotifyRuleOverlay({ cwd, project: 'crash' });
expect(existsSync(rulePath)).toBe(true);
const overlayRoot = join(hapiHome, 'cursor-notify-overlays');
const stateDirName = readdirSync(overlayRoot)[0];
expect(stateDirName).toBeTruthy();
const statePath = join(overlayRoot, stateDirName!, 'state.json');
const state = JSON.parse(readFileSync(statePath, 'utf-8')) as {
owners: Array<{ id: string; pid: number }>
snapshotTaken: boolean
restore: string | null
};
expect(state.snapshotTaken).toBe(true);
expect(state.restore).toBeNull();
state.owners = [{ id: 'dead', pid: 2_147_483_646 }];
writeFileSync(statePath, JSON.stringify(state));
const recovered = installCursorNotifyRuleOverlay({ cwd, project: 'after' });
recovered.cleanup();
expect(existsSync(rulePath)).toBe(false);
});
it('installs the alternate rule when the primary path is git-tracked', () => {
const primary = rulePathOf(cwd);
const alternate = join(cwd, '.cursor', 'rules', RULE_FILENAME_ALTERNATE);
mkdirSync(join(cwd, '.cursor', 'rules'), { recursive: true });
const tracked = [
'---',
'alwaysApply: true',
'---',
HAPI_SESSION_RULE_SENTINEL,
'',
'# Session status summary',
'',
'Tracked repo copy.',
''
].join('\n');
writeFileSync(primary, tracked, 'utf-8');
execFileSync('git', ['init'], { cwd });
execFileSync('git', ['add', `.cursor/rules/${RULE_FILENAME_PRIMARY}`], { cwd });
const overlay = installCursorNotifyRuleOverlay({ cwd, project: 'alt' });
expect(readFileSync(primary, 'utf-8')).toBe(tracked);
expect(overlay.rulePath).toBe(alternate);
expect(readFileSync(alternate, 'utf-8')).toContain('"project":"alt"');
overlay.cleanup();
expect(readFileSync(primary, 'utf-8')).toBe(tracked);
expect(existsSync(alternate)).toBe(false);
});
it('preserves a mid-session user replacement across another live install', () => {
const rulePath = rulePathOf(cwd);
const first = installCursorNotifyRuleOverlay({ cwd, project: 'alive' });
const userReplacement = '# operator replaced while A still live\n';
writeFileSync(rulePath, userReplacement, 'utf-8');
const second = installCursorNotifyRuleOverlay({ cwd, project: 'peer' });
expect(readFileSync(rulePath, 'utf-8')).toContain('"project":"peer"');
first.cleanup();
expect(readFileSync(rulePath, 'utf-8')).toContain('"project":"peer"');
second.cleanup();
expect(readFileSync(rulePath, 'utf-8')).toBe(userReplacement);
});
it('scopes restore snapshots to the selected rule path', () => {
const primary = rulePathOf(cwd);
const alternate = join(cwd, '.cursor', 'rules', RULE_FILENAME_ALTERNATE);
mkdirSync(join(cwd, '.cursor', 'rules'), { recursive: true });
const altUser = '# pre-existing alternate user rule\n';
writeFileSync(alternate, altUser, 'utf-8');
writeFileSync(primary, '# primary will be tracked\n', 'utf-8');
execFileSync('git', ['init'], { cwd });
execFileSync('git', ['add', `.cursor/rules/${RULE_FILENAME_PRIMARY}`], { cwd });
const overlay = installCursorNotifyRuleOverlay({ cwd, project: 'scoped' });
expect(overlay.rulePath).toBe(alternate);
expect(readFileSync(alternate, 'utf-8')).toContain('"project":"scoped"');
overlay.cleanup();
expect(readFileSync(alternate, 'utf-8')).toBe(altUser);
});
it('reaps git exclude leases left by crashed sessions', () => {
execFileSync('git', ['init'], { cwd });
const excludePath = join(cwd, '.git', 'info', 'exclude');
mkdirSync(dirname(excludePath), { recursive: true });
const deadLease = `${HAPI_NOTIFY_GIT_EXCLUDE_MARKER_PREFIX} 2147483646:dead-lease\n/.cursor/rules/${RULE_FILENAME_PRIMARY}\n`;
writeFileSync(excludePath, `# keep-me\n${deadLease}`, 'utf-8');
const overlay = installCursorNotifyRuleOverlay({ cwd, project: 'reap' });
const mid = readFileSync(excludePath, 'utf-8');
expect(mid).toContain('# keep-me');
expect(mid).not.toContain('2147483646:dead-lease');
expect(mid).toContain(HAPI_NOTIFY_GIT_EXCLUDE_MARKER_PREFIX);
overlay.cleanup();
expect(readFileSync(excludePath, 'utf-8')).toBe('# keep-me\n');
});
it('refuses to write through a symlinked rule path', () => {
if (process.platform === 'win32') return;
const rulePath = rulePathOf(cwd);
const outside = join(hapiHome, 'outside-target.mdc');
writeFileSync(outside, '# outside\n', 'utf-8');
mkdirSync(join(cwd, '.cursor', 'rules'), { recursive: true });
symlinkSync(outside, rulePath);
const overlay = installCursorNotifyRuleOverlay({ cwd, project: 'symlink' });
expect(readFileSync(outside, 'utf-8')).toBe('# outside\n');
expect(readFileSync(rulePath, 'utf-8')).toBe('# outside\n');
overlay.cleanup();
expect(readFileSync(outside, 'utf-8')).toBe('# outside\n');
});
it('shares ownership across realpath and symlink workspace aliases', () => {
if (process.platform === 'win32') return;
const alias = join(hapiHome, 'cwd-alias');
symlinkSync(cwd, alias);
const first = installCursorNotifyRuleOverlay({ cwd, project: 'real' });
const second = installCursorNotifyRuleOverlay({ cwd: alias, project: 'alias' });
expect(second.rulePath).toBe(first.rulePath);
expect(readFileSync(first.rulePath, 'utf-8')).toContain('"project":"alias"');
first.cleanup();
expect(existsSync(first.rulePath)).toBe(true);
second.cleanup();
expect(existsSync(first.rulePath)).toBe(false);
});
it('escapes bracketed path segments in git exclude patterns', () => {
expect(toLiteralGitExcludePattern('packages/[id]/.cursor/rules/hapi-session.mdc'))
.toBe('/packages/\\[id\\]/.cursor/rules/hapi-session.mdc');
const nested = join(cwd, 'packages', '[id]');
mkdirSync(nested, { recursive: true });
execFileSync('git', ['init'], { cwd });
const overlay = installCursorNotifyRuleOverlay({ cwd: nested, project: 'brackets' });
const exclude = readFileSync(join(cwd, '.git', 'info', 'exclude'), 'utf-8');
expect(exclude).toContain('/packages/\\[id\\]/.cursor/rules/');
const ignored = execFileSync(
'git',
['-C', cwd, 'check-ignore', '-v', '--', `packages/[id]/.cursor/rules/${RULE_FILENAME_PRIMARY}`],
{ encoding: 'utf-8' }
);
expect(ignored.length).toBeGreaterThan(0);
overlay.cleanup();
});
it('restores a post-crash user replacement instead of a stale snapshot', () => {
const rulePath = rulePathOf(cwd);
installCursorNotifyRuleOverlay({ cwd, project: 'crash' });
expect(existsSync(rulePath)).toBe(true);
const overlayRoot = join(hapiHome, 'cursor-notify-overlays');
const stateDirName = readdirSync(overlayRoot)[0];
expect(stateDirName).toBeTruthy();
const statePath = join(overlayRoot, stateDirName!, 'state.json');
const state = JSON.parse(readFileSync(statePath, 'utf-8')) as {
owners: Array<{ id: string; pid: number }>
snapshotTaken: boolean
restore: string | null
};
expect(state.restore).toBeNull();
state.owners = [{ id: 'dead', pid: 2_147_483_646 }];
writeFileSync(statePath, JSON.stringify(state));
const userReplacement = '# operator replaced generated rule after crash\n';
writeFileSync(rulePath, userReplacement, 'utf-8');
const recovered = installCursorNotifyRuleOverlay({ cwd, project: 'after' });
expect(readFileSync(rulePath, 'utf-8')).toContain('"project":"after"');
recovered.cleanup();
expect(readFileSync(rulePath, 'utf-8')).toBe(userReplacement);
});
it('excludes the transient rule from ordinary git staging', () => {
execFileSync('git', ['init'], { cwd });
const overlay = installCursorNotifyRuleOverlay({ cwd, project: 'stage' });
const exclude = readFileSync(join(cwd, '.git', 'info', 'exclude'), 'utf-8');
expect(exclude).toContain(HAPI_NOTIFY_GIT_EXCLUDE_MARKER_PREFIX);
expect(exclude).toContain(`/.cursor/rules/${RULE_FILENAME_PRIMARY}`);
const ignored = execFileSync(
'git',
['-C', cwd, 'check-ignore', '-v', `--`, `.cursor/rules/${RULE_FILENAME_PRIMARY}`],
{ encoding: 'utf-8' }
);
expect(ignored).toContain(`/.cursor/rules/${RULE_FILENAME_PRIMARY}`);
overlay.cleanup();
const after = readFileSync(join(cwd, '.git', 'info', 'exclude'), 'utf-8');
expect(after).not.toContain(HAPI_NOTIFY_GIT_EXCLUDE_MARKER_PREFIX);
});
it('preserves pre-existing .git/info/exclude rules across install and cleanup', () => {
execFileSync('git', ['init'], { cwd });
const excludePath = join(cwd, '.git', 'info', 'exclude');
writeFileSync(excludePath, '# keep-me\nlocal-notes.txt\n', 'utf-8');
const overlay = installCursorNotifyRuleOverlay({ cwd });
overlay.cleanup();
expect(readFileSync(excludePath, 'utf-8')).toBe('# keep-me\nlocal-notes.txt\n');
});
it('clears ownership state without recursively deleting a concurrent install dir', () => {
const first = installCursorNotifyRuleOverlay({ cwd, project: 'first' });
first.cleanup();
const second = installCursorNotifyRuleOverlay({ cwd, project: 'second' });
expect(readFileSync(second.rulePath, 'utf-8')).toContain('"project":"second"');
// Simulate last-owner cleanup racing a live peer: second still owns the cwd.
const third = installCursorNotifyRuleOverlay({ cwd, project: 'third' });
second.cleanup();
expect(readFileSync(third.rulePath, 'utf-8')).toContain('"project":"third"');
third.cleanup();
expect(existsSync(third.rulePath)).toBe(false);
});
it('preserves mid-session user replacement without sentinel', () => {
const rulePath = rulePathOf(cwd);
mkdirSync(join(cwd, '.cursor', 'rules'), { recursive: true });
writeFileSync(rulePath, '# prior\n', 'utf-8');
const overlay = installCursorNotifyRuleOverlay({ cwd, project: 'sess' });
const userReplacement = '# user replaced mid-session\n';
writeFileSync(rulePath, userReplacement, 'utf-8');
overlay.cleanup();
expect(readFileSync(rulePath, 'utf-8')).toBe(userReplacement);
});
it('resolves relative HAPI_HOME to an absolute path', () => {
const relName = `hapi-overlay-home-${Date.now()}`;
process.env.HAPI_HOME = relName;
const absHome = resolve(relName);
mkdirSync(join(cwd, '.cursor', 'rules'), { recursive: true });
writeFileSync(rulePathOf(cwd), '# tracked\n', 'utf-8');
const overlay = installCursorNotifyRuleOverlay({ cwd });
expect(existsSync(join(absHome, 'cursor-notify-overlays'))).toBe(true);
overlay.cleanup();
rmSync(absHome, { recursive: true, force: true });
});
it('never deletes a user file that replaced ours mid-session', () => {
const overlay = installCursorNotifyRuleOverlay({ cwd });
const userContent = 'the user clobbered our rule with their own\n';
writeFileSync(overlay.rulePath, userContent, 'utf-8');
overlay.cleanup();
expect(readFileSync(overlay.rulePath, 'utf-8')).toBe(userContent);
});
it('cleanup is idempotent', () => {
const overlay = installCursorNotifyRuleOverlay({ cwd });
overlay.cleanup();
expect(() => overlay.cleanup()).not.toThrow();
expect(existsSync(overlay.rulePath)).toBe(false);
});
it('skips install when an existing rule is unreadable', () => {
if (process.platform === 'win32') return;
const rulePath = rulePathOf(cwd);
mkdirSync(join(cwd, '.cursor', 'rules'), { recursive: true });
const prior = '# secret user rule\n';
writeFileSync(rulePath, prior, { mode: 0o600 });
chmodSync(rulePath, 0o000);
const overlay = installCursorNotifyRuleOverlay({ cwd, project: 'denied' });
chmodSync(rulePath, 0o600);
expect(readFileSync(rulePath, 'utf-8')).toBe(prior);
overlay.cleanup();
expect(readFileSync(rulePath, 'utf-8')).toBe(prior);
});
it('preserves the original rule file mode across install and cleanup', () => {
if (process.platform === 'win32') return;
const rulePath = rulePathOf(cwd);
mkdirSync(join(cwd, '.cursor', 'rules'), { recursive: true });
writeFileSync(rulePath, '# private\n', { mode: 0o600 });
expect(statSync(rulePath).mode & 0o777).toBe(0o600);
const overlay = installCursorNotifyRuleOverlay({ cwd, project: 'mode' });
expect(readFileSync(rulePath, 'utf-8')).toContain('"project":"mode"');
const stateDir = join(hapiHome, 'cursor-notify-overlays', readdirSync(join(hapiHome, 'cursor-notify-overlays'))[0]!);
expect(statSync(join(stateDir, 'state.json')).mode & 0o777).toBe(0o600);
overlay.cleanup();
expect(readFileSync(rulePath, 'utf-8')).toBe('# private\n');
expect(statSync(rulePath).mode & 0o777).toBe(0o600);
});
it('restores a crash-recovery snapshot when a later install fails before write', () => {
if (process.platform === 'win32') return;
const rulePath = rulePathOf(cwd);
mkdirSync(join(cwd, '.cursor', 'rules'), { recursive: true });
const prior = '# user rule before crash\n';
writeFileSync(rulePath, prior, 'utf-8');
// First session installs, then "crashes" without cleanup.
installCursorNotifyRuleOverlay({ cwd, project: 'crash' });
expect(readFileSync(rulePath, 'utf-8')).toContain('"project":"crash"');
const overlayRoot = join(hapiHome, 'cursor-notify-overlays');
const stateDirName = readdirSync(overlayRoot)[0];
expect(stateDirName).toBeTruthy();
const statePath = join(overlayRoot, stateDirName!, 'state.json');
const state = JSON.parse(readFileSync(statePath, 'utf-8')) as {
owners: Array<{ id: string; pid: number }>
snapshotTaken: boolean
restore: string | null
};
expect(state.restore).toBe(prior);
state.owners = [{ id: 'dead', pid: 2_147_483_646 }];
writeFileSync(statePath, JSON.stringify(state));
// Poison exclude so the recovery install registers ownership then fails
// before writing (exclude lease write throws). chmod after write — mode
// on writeFileSync is ignored when git init already created the file.
execFileSync('git', ['init'], { cwd });
const excludePath = join(cwd, '.git', 'info', 'exclude');
mkdirSync(dirname(excludePath), { recursive: true });
writeFileSync(excludePath, '# blocked\n', 'utf-8');
chmodSync(excludePath, 0o444);
const beforeFail = readFileSync(rulePath, 'utf-8');
const failed = installCursorNotifyRuleOverlay({ cwd, project: 'fail' });
// Failed handle must not have rewritten the crash-era generated rule.
expect(readFileSync(rulePath, 'utf-8')).toBe(beforeFail);
expect(beforeFail).toContain('"project":"crash"');
failed.cleanup();
chmodSync(excludePath, 0o644);
expect(readFileSync(rulePath, 'utf-8')).toBe(prior);
});
it('retains the restore snapshot when cleanup cannot read the generated rule', () => {
if (process.platform === 'win32') return;
const rulePath = rulePathOf(cwd);
mkdirSync(join(cwd, '.cursor', 'rules'), { recursive: true });
const prior = '# keep-me-across-unreadable-cleanup\n';
writeFileSync(rulePath, prior, { mode: 0o600 });
const overlay = installCursorNotifyRuleOverlay({ cwd, project: 'held' });
expect(readFileSync(rulePath, 'utf-8')).toContain('"project":"held"');
chmodSync(rulePath, 0o000);
overlay.cleanup();
const overlayRoot = join(hapiHome, 'cursor-notify-overlays');
const stateDirName = readdirSync(overlayRoot)[0];
expect(stateDirName).toBeTruthy();
const state = JSON.parse(readFileSync(join(overlayRoot, stateDirName!, 'state.json'), 'utf-8')) as {
owners: unknown[]
snapshotTaken: boolean
restore: string | null
};
expect(state.owners).toEqual([]);
expect(state.snapshotTaken).toBe(true);
expect(state.restore).toBe(prior);
chmodSync(rulePath, 0o600);
const recovered = installCursorNotifyRuleOverlay({ cwd, project: 'later' });
recovered.cleanup();
expect(readFileSync(rulePath, 'utf-8')).toBe(prior);
});
it('recreates ownership stateDir when a prior cleanup removed it', () => {
const first = installCursorNotifyRuleOverlay({ cwd, project: 'prior' });
const overlayRoot = join(hapiHome, 'cursor-notify-overlays');
const stateDirName = readdirSync(overlayRoot).find((name) => !name.endsWith('.lock'));
expect(stateDirName).toBeTruthy();
const stateDir = join(overlayRoot, stateDirName!);
first.cleanup();
// Simulate last-owner cleanup having removed the empty stateDir while a
// waiter had already decided to install against that path.
rmSync(stateDir, { recursive: true, force: true });
expect(existsSync(stateDir)).toBe(false);
const second = installCursorNotifyRuleOverlay({ cwd, project: 'waiter' });
expect(readFileSync(rulePathOf(cwd), 'utf-8')).toContain('"project":"waiter"');
expect(existsSync(join(stateDir, 'state.json'))).toBe(true);
second.cleanup();
expect(existsSync(rulePathOf(cwd))).toBe(false);
});
it('skips install when the ownership lock is abandoned (empty pre-token file)', () => {
mkdirSync(join(cwd, '.cursor', 'rules'), { recursive: true });
// Plant an abandoned ownership lock at the hashed path by letting a first
// install create the state dir, then leave a dead empty lock beside it.
const first = installCursorNotifyRuleOverlay({ cwd, project: 'seed' });
const overlayRoot = join(hapiHome, 'cursor-notify-overlays');
const stateDirName = readdirSync(overlayRoot)[0];
expect(stateDirName).toBeTruthy();
first.cleanup();
const lockPath = join(overlayRoot, `${stateDirName}.lock`);
writeFileSync(lockPath, '', 'utf-8'); // pre-token empty wx survivor
const blocked = installCursorNotifyRuleOverlay({ cwd, project: 'blocked' });
expect(existsSync(rulePathOf(cwd))).toBe(false);
blocked.cleanup();
expect(existsSync(lockPath)).toBe(true);
expect(readNotifyOverlayLockOwner(lockPath)).toBeNull();
unlinkSync(lockPath);
});
it('skips install when the exclude lock is abandoned by a dead PID', () => {
execFileSync('git', ['init'], { cwd });
const excludePath = join(cwd, '.git', 'info', 'exclude');
mkdirSync(dirname(excludePath), { recursive: true });
writeFileSync(excludePath, '', 'utf-8');
const excludeLock = `${excludePath}.hapi-notify.lock`;
writeFileSync(
excludeLock,
JSON.stringify({ pid: 2_147_483_646, token: 'dead-exclude-owner' }),
'utf-8'
);
const blocked = installCursorNotifyRuleOverlay({ cwd, project: 'exclude-lock' });
expect(existsSync(rulePathOf(cwd))).toBe(false);
blocked.cleanup();
expect(readNotifyOverlayLockOwner(excludeLock)?.token).toBe('dead-exclude-owner');
unlinkSync(excludeLock);
});
});
describe('withNotifyOverlayLock', () => {
let lockDir: string;
beforeEach(() => {
lockDir = mkdtempSync(join(tmpdir(), 'hapi-notify-lock-'));
});
afterEach(() => {
rmSync(lockDir, { recursive: true, force: true });
});
it('publishes pid+token and releases only its own lock', () => {
const lockPath = join(lockDir, 'state.lock');
withNotifyOverlayLock(lockPath, () => {
const owner = readNotifyOverlayLockOwner(lockPath);
expect(owner?.pid).toBe(process.pid);
expect(owner?.token).toMatch(/^[0-9a-f-]{36}$/i);
});
expect(existsSync(lockPath)).toBe(false);
});
it('fails closed on an abandoned empty lock with an actionable message', () => {
const lockPath = join(lockDir, 'abandoned.lock');
writeFileSync(lockPath, '', 'utf-8');
expect(() => withNotifyOverlayLock(lockPath, () => {})).toThrow(
/Stale Cursor notify-rule overlay lock:.*rm -f/
);
expect(existsSync(lockPath)).toBe(true);
expect(readNotifyOverlayLockOwner(lockPath)).toBeNull();
});
it('fails closed on a dead-PID lock instead of pathname-stealing', () => {
const lockPath = join(lockDir, 'dead.lock');
writeFileSync(lockPath, JSON.stringify({ pid: 2_147_483_646, token: 'dead-owner' }), 'utf-8');
expect(() => withNotifyOverlayLock(lockPath, () => {})).toThrow(
/Stale Cursor notify-rule overlay lock:/
);
expect(readNotifyOverlayLockOwner(lockPath)?.token).toBe('dead-owner');
});
it('does not unlink a successor lock on release', () => {
const lockPath = join(lockDir, 'successor.lock');
withNotifyOverlayLock(lockPath, () => {
writeFileSync(lockPath, JSON.stringify({ pid: process.pid, token: 'successor-token' }), 'utf-8');
});
expect(existsSync(lockPath)).toBe(true);
expect(readNotifyOverlayLockOwner(lockPath)?.token).toBe('successor-token');
unlinkSync(lockPath);
});
it('classifies a lock that disappeared after EEXIST as retry, not stale', () => {
const lockPath = join(lockDir, 'gone-after-eexist.lock');
expect(existsSync(lockPath)).toBe(false);
expect(classifyContendedNotifyOverlayLock(lockPath)).toBe('retry');
});
it('classifies live vs abandoned contended locks', () => {
const livePath = join(lockDir, 'live.lock');
writeFileSync(livePath, JSON.stringify({ pid: process.pid, token: 'live' }), 'utf-8');
expect(classifyContendedNotifyOverlayLock(livePath)).toBe('wait');
const deadPath = join(lockDir, 'dead-held.lock');
writeFileSync(deadPath, JSON.stringify({ pid: 2_147_483_646, token: 'dead' }), 'utf-8');
expect(classifyContendedNotifyOverlayLock(deadPath)).toBe('stale');
const emptyPath = join(lockDir, 'empty-held.lock');
writeFileSync(emptyPath, '', 'utf-8');
expect(classifyContendedNotifyOverlayLock(emptyPath)).toBe('stale');
});
it('retries when the lock is removed after existsSync but before the owner read', () => {
const lockPath = join(lockDir, 'gone-during-read.lock');
expect(
classifyContendedNotifyOverlayLock(lockPath, {
exists: () => true,
read: () => ({ status: 'missing' })
})
).toBe('retry');
});
});
@@ -0,0 +1,891 @@
/**
* Per-session, workspace-local Cursor rule overlay for session status summaries.
*
* Cursor ACP has no HAPI-controlled system-prompt channel (unlike Claude / Codex /
* OpenCode / Grok). It discovers rules from workspace `.cursor/rules/*.mdc`
* files (plain `.md` is ignored) and global `~/.cursor` user rules. Editing the
* global user rules would pollute the operator's non-HAPI Cursor experience, so
* we install a transient, repo-local rule for the lifetime of a session and
* remove it on teardown — only when the emit status-summary setting is on.
*
* Concurrent sessions sharing a cwd share ownership state under HAPI_HOME (not
* inside the workspace) with live PIDs so: (1) only the last live owner restores
* the pre-HAPI file, (2) crashed owners are reaped on the next install, and
* (3) `git add -A` cannot stage bookkeeping sidecars.
*
* Non-clobbering discipline (mirrors how a config overlay behaves): if the user
* already has a file at the same path we back up its contents and restore them on
* cleanup; a file that already carries our sentinel is one of ours (a prior or
* concurrent session in the same cwd), so we never treat it as user content —
* UNLESS git tracks that path (then we fall through to an alternate filename).
* All fs work is fail-open — a missing rule must never crash a session.
*/
import { spawnSync } from 'node:child_process';
import { createHash, randomUUID } from 'node:crypto';
import {
existsSync,
linkSync,
lstatSync,
mkdirSync,
readFileSync,
readdirSync,
realpathSync,
renameSync,
rmdirSync,
rmSync,
unlinkSync,
writeFileSync
} from 'node:fs';
import { homedir } from 'node:os';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { SESSION_SUMMARY_CONTRACT_LINE } from '@/modules/common/sessionSummaryInstruction';
import { logger } from '@/ui/logger';
import { isProcessAlive } from '@/utils/process';
/** Preferred rule filename; fall back when Git already tracks this path. */
export const RULE_FILENAME_PRIMARY = 'hapi-session.mdc';
/** Alternate when the primary path is git-tracked (still alwaysApply). */
export const RULE_FILENAME_ALTERNATE = 'hapi-session-summary.mdc';
const RULE_CANDIDATES = [RULE_FILENAME_PRIMARY, RULE_FILENAME_ALTERNATE] as const;
const OWNERSHIP_LOCK_RETRY_INTERVAL_MS = 50;
const OWNERSHIP_LOCK_MAX_ATTEMPTS = 100;
/** Prefix for `.git/info/exclude` lease markers (do not commit transient rule). */
export const HAPI_NOTIFY_GIT_EXCLUDE_MARKER_PREFIX = '# hapi-cursor-notify-rule';
/**
* Hidden marker identifying files this overlay owns. Lets us distinguish a
* user's pre-existing rule (back up + restore) from one written by another HAPI
* session sharing the cwd.
*/
export const HAPI_SESSION_RULE_SENTINEL = '<!-- hapi:session-summary-rule -->';
export interface CursorNotifyRuleOverlay {
/** Absolute path of the rule file this overlay manages. */
readonly rulePath: string;
/** Restore any pre-existing user file / remove ours, prune dirs we created. */
cleanup: () => void;
}
export interface InstallCursorNotifyRuleOverlayOptions {
/** Workspace root cursor-agent is spawned in (session.path). */
cwd: string;
/** Optional project name to bake into the example line. */
project?: string | null;
/** Optional agent id to bake into the example line. */
agentId?: string | null;
}
type OverlayOwner = {
/** Unique per install (same PID can own multiple overlays in tests / nested launches). */
id: string;
pid: number;
};
/** Published into ownership / exclude lock files so release can avoid unlinking a successor. */
export type NotifyOverlayLockOwner = {
pid: number;
token: string;
};
type OverlayOwnershipState = {
cwd: string;
owners: OverlayOwner[];
/**
* True once we have snapshotted the pre-HAPI rule state for this cwd.
* Distinguishes "never captured" from "captured as absent" (`restore: null`).
*/
snapshotTaken: boolean;
/** Pre-HAPI rule bytes when `snapshotTaken`; null means no file existed. */
restore: string | null;
/** Pre-HAPI file mode bits (permission only) when restore content was captured. */
restoreMode: number | null;
};
type RuleFileRead =
| { status: 'absent' }
| { status: 'ok'; content: string; mode: number }
| { status: 'error'; error: unknown };
type RuleTarget = {
ruleFilename: string;
/** Repo-relative path using `/` separators (git exclude / ls-files). */
ruleRelPosix: string;
rulePath: string;
};
/**
* Build the `.mdc` rule content. `alwaysApply: true` so cursor-agent applies it
* to every turn without the agent having to opt in. Kept deliberately benign and
* functional: it reads as ordinary session-tracking config, not surveillance.
*
* Contract and #2267 post-done silence match `buildSessionSummaryInstruction`.
*/
export function buildNotifyRuleContent(opts: { project?: string | null; agentId?: string | null } = {}): string {
const project = sanitizeToken(opts.project) ?? '<project>';
const agentId = sanitizeToken(opts.agentId) ?? '<agent-id>';
const exampleLine = SESSION_SUMMARY_CONTRACT_LINE
.replace('"agent":"<agent-id>"', `"agent":"${agentId}"`)
.replace('"project":"<project>"', `"project":"${project}"`);
const exampleNoAction = `AGENT_NOTIFY_SUMMARY {"version":1,"agent":"${agentId}","project":"${project}","status":"done","summary":"one-line triage"}`;
return [
'---',
'alwaysApply: true',
'---',
HAPI_SESSION_RULE_SENTINEL,
'',
'# Session status summary',
'',
'At the end of each turn, append exactly one machine-readable status line',
'(no backticks) to the final answer only, so this workspace\'s session tracking',
'can record progress. Do not emit this line in commentary, progress updates, or before tool calls.',
'Put it on its own final line after all other content:',
'',
exampleLine,
'',
'When nothing remains, omit the action key entirely (example):',
exampleNoAction,
'',
'Guidance:',
'- Use the language used by the user in the current conversation for the',
' human-readable "action" and "summary" values.',
'- status: pick the closest value; use "blocked" if unsure.',
'- action: only when status is "done" and follow-up remains; 12 words or fewer.',
' Omit the action key when nothing remains. Never emit "action":"" —',
' Cursor drops a quote and breaks JSON.',
'- summary: one-line triage of the turn outcome.',
'- Keep it as the very last line of every response.',
// Cross-turn close (#2267): status "done" ends the spoken unit.
'After status "done", do not emit further user-visible replies for redundant',
'background task-complete notifications until the user sends new intent.',
''
].join('\n');
}
/**
* Install the rule file under `<cwd>/.cursor/rules/`, backing up any
* pre-existing user file. Returns an overlay handle whose `cleanup()` restores
* the prior state. Never throws: on failure it returns a no-op cleanup so callers
* can wire it unconditionally.
*/
export function installCursorNotifyRuleOverlay(
opts: InstallCursorNotifyRuleOverlayOptions
): CursorNotifyRuleOverlay {
const absCwd = canonicalizeExistingPath(resolve(opts.cwd));
const cursorDir = join(absCwd, '.cursor');
const rulesDir = join(cursorDir, 'rules');
const target = resolveRuleTarget(absCwd);
const rulePath = target?.rulePath ?? join(rulesDir, RULE_FILENAME_PRIMARY);
const ruleRelPosix = target?.ruleRelPosix ?? `.cursor/rules/${RULE_FILENAME_PRIMARY}`;
// Ownership / lock / restore snapshot are scoped to the selected rule path
// so primary vs alternate installs never share a restore target.
const stateDir = getOverlayStateDir(absCwd, ruleRelPosix);
const statePath = join(stateDir, 'state.json');
// Lock lives beside stateDir so last-owner cleanup can clear state.json
// while holding the lock without recursively deleting the lock's parent.
const lockPath = `${stateDir}.lock`;
const ownerId = randomUUID();
const pid = process.pid;
const excludeLeaseId = `${pid}:${ownerId}`;
// Dirs we create so cleanup can prune exactly what we added (deepest first).
const createdDirs: string[] = [];
let cleaned = false;
/** Owner row written to HAPI_HOME state (even if the workspace rule write fails). */
let registered = false;
/** Workspace rule successfully overwritten with generated content. */
let installed = false;
let undoGitExclude: (() => void) | null = null;
if (!target) {
logger.debug('[cursor-notify-rule] skip install — all candidate rule paths are git-tracked');
return {
rulePath,
cleanup: () => {
if (cleaned) return;
cleaned = true;
}
};
}
try {
assertNotSymlinkPath(cursorDir, 'Cursor config directory');
assertNotSymlinkPath(rulesDir, 'Cursor rules directory');
assertNotSymlinkPath(rulePath, 'Cursor session rule');
if (!existsSync(cursorDir)) {
mkdirSync(cursorDir, { recursive: true });
createdDirs.push(cursorDir);
}
if (!existsSync(rulesDir)) {
mkdirSync(rulesDir, { recursive: true });
createdDirs.push(rulesDir);
}
// Re-check after mkdir: a race could replace a created dir with a symlink.
assertNotSymlinkPath(cursorDir, 'Cursor config directory');
assertNotSymlinkPath(rulesDir, 'Cursor rules directory');
withOwnershipLock(lockPath, () => {
// Create under the lock so a concurrent last-owner cleanup that
// emptied/removed stateDir cannot leave writeOwnershipState with ENOENT.
mkdirSync(stateDir, { recursive: true });
let state = reapOwners(readOwnershipState(statePath, absCwd));
const current = readRuleFile(rulePath);
if (current.status === 'error') {
// Cannot back up an existing rule — refuse to clobber it.
throw new Error(
`Refusing Cursor notify-rule install: cannot read existing rule at ${rulePath}`
);
}
const stillOurs = current.status === 'ok'
&& current.content.includes(HAPI_SESSION_RULE_SENTINEL);
// Always refresh when the on-disk file is non-HAPI user content —
// including while another session is still live — so a mid-session
// operator replacement is what last-owner cleanup restores.
if (current.status === 'ok' && !stillOurs) {
state = {
cwd: absCwd,
owners: state.owners,
snapshotTaken: true,
restore: current.content,
restoreMode: current.mode
};
} else if (state.owners.length === 0 && !state.snapshotTaken) {
// First install (or recovered empty state): capture pre-HAPI bytes,
// including an explicit "file was absent" snapshot.
state = {
cwd: absCwd,
owners: [],
snapshotTaken: true,
restore: current.status === 'ok' ? current.content : null,
restoreMode: current.status === 'ok' ? current.mode : null
};
} else if (state.owners.length === 0) {
// Crash recovery with our generated rule still present: keep the
// prior snapshot (including restore:null).
state = { ...state, owners: [] };
}
state.owners.push({ id: ownerId, pid });
writeOwnershipState(statePath, state);
registered = true;
});
undoGitExclude = installGitExcludeLease(absCwd, rulePath, excludeLeaseId);
writeRuleFileNoFollow(rulePath, buildNotifyRuleContent(opts));
installed = true;
logger.debug(`[cursor-notify-rule] installed alwaysApply rule at ${rulePath}`);
} catch (error) {
if (error instanceof Error && error.message.startsWith('Stale Cursor notify-rule overlay lock:')) {
// Fail-open for the session, but loud enough that operators can rm the lock.
logger.warn('[cursor-notify-rule] install blocked by abandoned lock', error.message);
} else {
logger.debug('[cursor-notify-rule] install failed', error);
}
try {
undoGitExclude?.();
} catch {
// ignore
}
undoGitExclude = null;
}
const cleanup = (): void => {
if (cleaned) return;
cleaned = true;
if (!registered) {
try {
undoGitExclude?.();
} catch {
// ignore
}
return;
}
try {
withOwnershipLock(lockPath, () => {
let state = reapOwners(readOwnershipState(statePath, absCwd));
state.owners = state.owners.filter((owner) => owner.id !== ownerId);
if (state.owners.length > 0) {
writeOwnershipState(statePath, state);
return;
}
// Last live owner. Restore from the shared snapshot whenever the
// on-disk rule is still HAPI-owned (or absent) — including when
// *this* handle never finished install (crash-recovery peer that
// registered then failed). Mid-session user replacements without
// the sentinel are left alone.
const current = readRuleFile(rulePath);
if (current.status === 'error') {
// Cannot verify ownership — leave the rule alone, but keep
// the restore snapshot so a later session can recover it.
writeOwnershipState(statePath, {
cwd: absCwd,
owners: [],
snapshotTaken: state.snapshotTaken,
restore: state.restore,
restoreMode: state.restoreMode
});
return;
}
const stillOurs = current.status === 'absent'
|| current.content.includes(HAPI_SESSION_RULE_SENTINEL);
if (stillOurs) {
if (state.snapshotTaken && state.restore !== null) {
writeRuleFileNoFollow(
rulePath,
state.restore,
state.restoreMode ?? undefined
);
} else if (state.snapshotTaken && state.restore === null) {
if (lstatSync(rulePath, { throwIfNoEntry: false })) {
unlinkSync(rulePath);
}
}
}
// Clear ownership state while still holding the lock. Keep
// stateDir itself persistent — removing it after unlock races a
// waiter that is about to mkdir/write under the same path.
try {
if (existsSync(statePath)) {
unlinkSync(statePath);
}
} catch {
// ignore
}
});
try {
undoGitExclude?.();
} catch (error) {
logger.debug('[cursor-notify-rule] git exclude cleanup failed', error);
}
undoGitExclude = null;
for (const dir of [...createdDirs].reverse()) {
if (isEmptyDir(dir)) {
rmdirSync(dir);
}
}
} catch (error) {
logger.debug('[cursor-notify-rule] cleanup failed', error);
}
};
return { rulePath, cleanup };
}
/** Pick the first candidate rule path that Git does not already track. */
export function resolveRuleTarget(absCwd: string): RuleTarget | null {
for (const ruleFilename of RULE_CANDIDATES) {
const ruleRelPosix = `.cursor/rules/${ruleFilename}`;
if (!isGitTrackedPath(absCwd, ruleRelPosix)) {
return {
ruleFilename,
ruleRelPosix,
rulePath: join(absCwd, '.cursor', 'rules', ruleFilename)
};
}
}
return null;
}
function isGitTrackedPath(cwd: string, relPosix: string): boolean {
const probe = spawnSync('git', ['-C', cwd, 'ls-files', '--error-unmatch', '--', relPosix], {
encoding: 'utf-8',
stdio: ['ignore', 'ignore', 'ignore']
});
return probe.status === 0;
}
function installGitExcludeLease(absCwd: string, rulePath: string, leaseId: string): (() => void) | null {
const top = spawnSync('git', ['rev-parse', '--show-toplevel'], {
cwd: absCwd,
encoding: 'utf-8'
});
if (top.status !== 0) {
return null;
}
const root = top.stdout.trim();
if (!root) {
return null;
}
const relRaw = relative(root, rulePath);
if (!relRaw || relRaw.startsWith('..') || isAbsolute(relRaw)) {
return null;
}
const pattern = toLiteralGitExcludePattern(relRaw);
const excludePath = resolveGitExcludePath(root);
if (!excludePath) {
return null;
}
withExcludeLock(`${excludePath}.hapi-notify.lock`, () => {
pruneDeadExcludeLeasesUnlocked(excludePath);
appendExcludeLeaseUnlocked(excludePath, pattern, leaseId);
});
return () => {
withExcludeLock(`${excludePath}.hapi-notify.lock`, () => {
pruneDeadExcludeLeasesUnlocked(excludePath);
removeExcludeLeaseUnlocked(excludePath, pattern, leaseId);
});
};
}
/**
* Encode a repo-relative path as an anchored literal Git exclude pattern
* (escape glob / character-class metacharacters; leading `/` anchors at root).
*/
export function toLiteralGitExcludePattern(relPath: string): string {
const posix = relPath.replaceAll('\\', '/').replace(/^\/+/, '');
const escaped = posix
.split('/')
.map((segment) => {
const escapedMeta = segment.replace(/([\\*?[\]])/g, '\\$1');
return escapedMeta.replace(/^([#!])/, '\\$1');
})
.join('/');
return `/${escaped}`;
}
function resolveGitExcludePath(root: string): string | null {
const excludeProc = spawnSync('git', ['rev-parse', '--git-path', 'info/exclude'], {
cwd: root,
encoding: 'utf-8'
});
if (excludeProc.status !== 0) {
return null;
}
const raw = excludeProc.stdout.trim();
if (!raw) {
return null;
}
return isAbsolute(raw) ? raw : resolve(root, raw);
}
function hapiNotifyGitExcludeMarker(leaseId: string): string {
return `${HAPI_NOTIFY_GIT_EXCLUDE_MARKER_PREFIX} ${leaseId}`;
}
function parseExcludeLeasePid(leaseId: string): number | null {
const match = /^(\d+):/.exec(leaseId);
if (!match) {
return null;
}
const parsed = Number(match[1]);
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
}
function appendExcludeLeaseUnlocked(excludePath: string, pattern: string, leaseId: string): void {
const marker = hapiNotifyGitExcludeMarker(leaseId);
const existing = existsSync(excludePath) ? readFileSync(excludePath, 'utf-8') : '';
const lines = existing.split(/\r?\n/);
if (lines.includes(marker)) {
return;
}
mkdirSync(dirname(excludePath), { recursive: true });
const prefix = existing.length === 0 || existing.endsWith('\n') ? '' : '\n';
writeFileSync(excludePath, `${existing}${prefix}${marker}\n${pattern}\n`, {
encoding: 'utf-8',
mode: 0o644
});
}
function removeExcludeLeaseUnlocked(excludePath: string, pattern: string, leaseId: string): void {
if (!existsSync(excludePath)) {
return;
}
const marker = hapiNotifyGitExcludeMarker(leaseId);
const lines = readFileSync(excludePath, 'utf-8').split(/\r?\n/);
const out: string[] = [];
for (let i = 0; i < lines.length; i++) {
if (lines[i] === marker && lines[i + 1] === pattern) {
i += 1;
continue;
}
out.push(lines[i]!);
}
while (out.length > 0 && out[out.length - 1] === '') {
out.pop();
}
const body = out.length === 0 ? '' : `${out.join('\n')}\n`;
writeFileSync(excludePath, body, { encoding: 'utf-8', mode: 0o644 });
}
/** Drop lease blocks whose owner PID is confirmed dead (crash recovery). */
function pruneDeadExcludeLeasesUnlocked(excludePath: string): void {
if (!existsSync(excludePath)) {
return;
}
const lines = readFileSync(excludePath, 'utf-8').split(/\r?\n/);
const out: string[] = [];
let removed = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i]!;
if (line.startsWith(`${HAPI_NOTIFY_GIT_EXCLUDE_MARKER_PREFIX} `)) {
const leaseId = line.slice(HAPI_NOTIFY_GIT_EXCLUDE_MARKER_PREFIX.length + 1).trim();
const leasePid = parseExcludeLeasePid(leaseId);
if (leasePid !== null && !isProcessAlive(leasePid)) {
removed = true;
if (lines[i + 1] !== undefined) {
i += 1;
}
continue;
}
}
out.push(line);
}
if (!removed) {
return;
}
while (out.length > 0 && out[out.length - 1] === '') {
out.pop();
}
const body = out.length === 0 ? '' : `${out.join('\n')}\n`;
writeFileSync(excludePath, body, { encoding: 'utf-8', mode: 0o644 });
}
function withExcludeLock(lockPath: string, fn: () => void): void {
withOwnershipLock(lockPath, fn);
}
/** Discriminated lock-file read so ENOENT is not collapsed into "invalid". */
export type NotifyOverlayLockOwnerRead =
| { status: 'ok'; owner: NotifyOverlayLockOwner }
| { status: 'missing' }
| { status: 'invalid' };
/**
* Read a notify-overlay lock owner record, distinguishing absence from
* empty/corrupt contents (including pre-token empty `wx` survivors).
*/
export function readNotifyOverlayLockOwnerStatus(lockPath: string): NotifyOverlayLockOwnerRead {
try {
const parsed = JSON.parse(readFileSync(lockPath, 'utf-8')) as unknown;
if (
parsed !== null
&& typeof parsed === 'object'
&& typeof (parsed as NotifyOverlayLockOwner).pid === 'number'
&& typeof (parsed as NotifyOverlayLockOwner).token === 'string'
) {
return { status: 'ok', owner: parsed as NotifyOverlayLockOwner };
}
return { status: 'invalid' };
} catch (error) {
const code = error && typeof error === 'object' && 'code' in error
? (error as { code?: string }).code
: undefined;
if (code === 'ENOENT') {
return { status: 'missing' };
}
return { status: 'invalid' };
}
}
/** Convenience: owner record or null (missing / invalid). */
export function readNotifyOverlayLockOwner(lockPath: string): NotifyOverlayLockOwner | null {
const read = readNotifyOverlayLockOwnerStatus(lockPath);
return read.status === 'ok' ? read.owner : null;
}
/** Fail closed for lock recovery: only ESRCH means the holder is confirmed gone. */
function isLockHolderAlive(pid: number): boolean {
if (pid <= 0) {
return false;
}
try {
process.kill(pid, 0);
return true;
} catch (error) {
const code = error && typeof error === 'object' && 'code' in error
? (error as { code?: string }).code
: undefined;
return code !== 'ESRCH';
}
}
function staleNotifyOverlayLockError(lockPath: string): Error {
return new Error(
`Stale Cursor notify-rule overlay lock: ${lockPath}; remove it and retry `
+ `(e.g. rm -f ${JSON.stringify(lockPath)})`
);
}
export type ClassifyContendedNotifyOverlayLockDeps = {
exists?: (path: string) => boolean;
read?: (path: string) => NotifyOverlayLockOwnerRead;
};
/**
* After link(2) EEXIST: decide whether to wait on a live holder, retry because
* the lock disappeared, or fail closed on an abandoned / corrupt lock file.
* Optional deps exist for regression coverage of the exists→read TOCTOU.
*/
export function classifyContendedNotifyOverlayLock(
lockPath: string,
deps: ClassifyContendedNotifyOverlayLockDeps = {}
): 'wait' | 'retry' | 'stale' {
const exists = deps.exists ?? ((path: string) => existsSync(path));
const read = deps.read ?? readNotifyOverlayLockOwnerStatus;
if (!exists(lockPath)) {
return 'retry';
}
const existing = read(lockPath);
if (existing.status === 'missing') {
// Holder released between existsSync and the owner read.
return 'retry';
}
if (existing.status === 'ok' && isLockHolderAlive(existing.owner.pid)) {
return 'wait';
}
return 'stale';
}
/**
* Exclusive cross-process lock for ownership state and `.git/info/exclude` leases.
* Owner JSON is published atomically via link(2) from a fully-written staging file.
* Stale/dead locks fail closed — pathname check-then-unlink can steal a successor's
* live lock under concurrent recoverers. Release unlinks only when the path still
* holds this owner's token.
*/
export function withNotifyOverlayLock(lockPath: string, fn: () => void): void {
withOwnershipLock(lockPath, fn);
}
function canonicalizeExistingPath(path: string): string {
try {
return realpathSync(path);
} catch {
return path;
}
}
function assertNotSymlinkPath(path: string, label: string): void {
const entry = lstatSync(path, { throwIfNoEntry: false });
if (entry?.isSymbolicLink()) {
throw new Error(`Refusing a symlinked ${label}: ${path}`);
}
}
/**
* Write without following an existing symlink: refuse links, then replace via
* temp+rename (rename replaces a symlink inode rather than writing through it).
*/
function writeRuleFileNoFollow(path: string, contents: string, mode: number = 0o644): void {
assertNotSymlinkPath(path, 'Cursor session rule');
const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
try {
writeFileSync(tmp, contents, { encoding: 'utf-8', mode: mode & 0o777 });
renameSync(tmp, path);
assertNotSymlinkPath(path, 'Cursor session rule');
} finally {
rmSync(tmp, { force: true });
}
}
function readRuleFile(path: string): RuleFileRead {
const entry = lstatSync(path, { throwIfNoEntry: false });
if (!entry) {
return { status: 'absent' };
}
if (entry.isSymbolicLink()) {
return { status: 'error', error: new Error(`symlinked rule: ${path}`) };
}
try {
return {
status: 'ok',
content: readFileSync(path, 'utf-8'),
mode: entry.mode & 0o777
};
} catch (error) {
return { status: 'error', error };
}
}
function getHapiHomeDir(): string {
const fromEnv = process.env.HAPI_HOME?.trim();
if (fromEnv) {
const expanded = fromEnv.replace(/^~(?=$|[/\\])/, homedir());
return isAbsolute(expanded) ? expanded : resolve(expanded);
}
return join(homedir(), '.hapi');
}
function getOverlayStateDir(absCwd: string, ruleRelPosix: string): string {
const hash = createHash('sha256').update(`${absCwd}\0${ruleRelPosix}`).digest('hex').slice(0, 24);
return join(getHapiHomeDir(), 'cursor-notify-overlays', hash);
}
function emptyOwnershipState(absCwd: string): OverlayOwnershipState {
return { cwd: absCwd, owners: [], snapshotTaken: false, restore: null, restoreMode: null };
}
function readOwnershipState(path: string, absCwd: string): OverlayOwnershipState {
const raw = safeRead(path);
if (!raw) {
return emptyOwnershipState(absCwd);
}
try {
const parsed = JSON.parse(raw) as Partial<OverlayOwnershipState>;
const owners: OverlayOwner[] = [];
if (Array.isArray(parsed.owners)) {
for (const entry of parsed.owners) {
if (
entry
&& typeof entry === 'object'
&& typeof (entry as OverlayOwner).id === 'string'
&& typeof (entry as OverlayOwner).pid === 'number'
&& Number.isFinite((entry as OverlayOwner).pid)
) {
owners.push({ id: (entry as OverlayOwner).id, pid: (entry as OverlayOwner).pid });
}
}
}
const snapshotTaken = parsed.snapshotTaken === true
|| typeof parsed.restore === 'string'
|| owners.length > 0;
return {
cwd: absCwd,
owners,
snapshotTaken,
restore: typeof parsed.restore === 'string' ? parsed.restore : null,
restoreMode: typeof parsed.restoreMode === 'number' && Number.isFinite(parsed.restoreMode)
? parsed.restoreMode & 0o777
: null
};
} catch {
return emptyOwnershipState(absCwd);
}
}
function writeOwnershipState(path: string, state: OverlayOwnershipState): void {
// Private + atomic: restore may be the only backup of a user's rule body.
// Truncating state.json in place would lose that backup on a partial write.
mkdirSync(dirname(path), { recursive: true });
const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
try {
writeFileSync(tmp, JSON.stringify(state), { encoding: 'utf-8', mode: 0o600 });
renameSync(tmp, path);
} finally {
rmSync(tmp, { force: true });
}
}
function reapOwners(state: OverlayOwnershipState): OverlayOwnershipState {
return {
...state,
owners: state.owners.filter((owner) => isProcessAlive(owner.pid))
};
}
function withOwnershipLock(lockPath: string, fn: () => void): void {
let attempts = 0;
let owner: NotifyOverlayLockOwner | undefined;
mkdirSync(dirname(lockPath), { recursive: true });
while (attempts < OWNERSHIP_LOCK_MAX_ATTEMPTS) {
owner = { pid: process.pid, token: randomUUID() };
const candidate = `${lockPath}.${owner.token}.tmp`;
try {
writeFileSync(candidate, JSON.stringify(owner), {
encoding: 'utf-8',
flag: 'wx',
mode: 0o600
});
try {
linkSync(candidate, lockPath);
break;
} catch (err: unknown) {
const code = err && typeof err === 'object' && 'code' in err
? (err as { code?: string }).code
: undefined;
if (code !== 'EEXIST') {
throw err;
}
attempts++;
// Holder may release between our EEXIST and the owner read —
// treat a missing lock as free and retry, not as abandoned.
const verdict = classifyContendedNotifyOverlayLock(lockPath);
if (verdict === 'retry' || verdict === 'wait') {
sleepSync(OWNERSHIP_LOCK_RETRY_INTERVAL_MS);
} else {
// Empty (pre-token), corrupt, or dead-PID lock — fail closed with
// an actionable recovery path. Do not pathname-steal.
throw staleNotifyOverlayLockError(lockPath);
}
} finally {
rmSync(candidate, { force: true });
}
continue;
} catch (err: unknown) {
rmSync(candidate, { force: true });
if (err instanceof Error && err.message.startsWith('Stale Cursor notify-rule overlay lock:')) {
throw err;
}
const code = err && typeof err === 'object' && 'code' in err
? (err as { code?: string }).code
: undefined;
if (code === 'EEXIST') {
attempts++;
sleepSync(OWNERSHIP_LOCK_RETRY_INTERVAL_MS);
continue;
}
throw err;
}
}
if (!owner || !existsSync(lockPath) || readNotifyOverlayLockOwner(lockPath)?.token !== owner.token) {
throw new Error(`Timed out waiting for Cursor notify-rule overlay lock: ${lockPath}`);
}
try {
fn();
} finally {
try {
if (readNotifyOverlayLockOwner(lockPath)?.token === owner.token) {
unlinkSync(lockPath);
}
} catch {
// ignore
}
}
}
function sleepSync(ms: number): void {
const sab = new SharedArrayBuffer(4);
const ia = new Int32Array(sab);
Atomics.wait(ia, 0, 0, ms);
}
function safeRead(path: string): string | null {
try {
return readFileSync(path, 'utf-8');
} catch {
return null;
}
}
function isEmptyDir(path: string): boolean {
try {
return readdirSync(path).length === 0;
} catch {
return false;
}
}
/**
* Keep only characters safe to bake into a JSON string example (no quotes/braces/
* newlines). Returns null for empty/whitespace so callers fall back to the
* placeholder token.
*/
function sanitizeToken(value: string | null | undefined): string | null {
if (typeof value !== 'string') return null;
const cleaned = value.replace(/[^A-Za-z0-9._\- /]/g, '').trim();
return cleaned.length > 0 ? cleaned : null;
}
@@ -1,10 +1,10 @@
/**
* Optional session-status summary instruction for non-Cursor agent flavors.
* Optional session-status summary instruction for agent flavors with a
* system-prompt / developer-instructions seam (Claude / Codex / OpenCode / Grok).
*
* Cursor ACP has no system-prompt / rules-overlay seam in upstream today, so
* it is intentionally not covered here. Claude / Codex / OpenCode / Grok get
* this text via their existing system-prompt / developer-instructions /
* one-shot instruction paths when the operator opts in.
* Cursor ACP has no HAPI system-prompt channel; when this toggle is on, the
* Cursor ACP launcher installs a transient workspace `.cursor/rules` overlay
* (`installCursorNotifyRuleOverlay`) instead — same opt-in gate, different inject path.
*
* Resolution order:
* 1. Explicit `HAPI_SESSION_SUMMARY_CONTRACT` env (0|false|off|no → off; anything else → on)