@cortex-agent/server 2026.9.14 → 2026.9.21
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/README.md +3 -2
- package/defaults/config/hooks/08-agents-md-injector-post-tool.json +10 -0
- package/defaults/config/hooks/{10-cortex-md-injector-session-start.json → 10-agents-md-injector-session-start.json} +3 -3
- package/defaults/config/hooks/{CORTEX.md → AGENTS.md} +2 -2
- package/defaults/hooks/{CORTEX.md → AGENTS.md} +1 -1
- package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
- package/defaults/hooks/cortex-hook-api.mjs +2 -2
- package/defaults/hooks/new-session-hook.mjs +2 -2
- package/defaults/hooks/rules-loader.mjs +2 -2
- package/defaults/hooks/status-md-guard.mjs +8 -8
- package/defaults/hooks/task-status-check.mjs +18 -76
- package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
- package/defaults/plugins/cortex-commission/.claude-plugin/plugin.json +2 -2
- package/defaults/plugins/cortex-commission/plugin.json +2 -2
- package/defaults/plugins/cortex-commission/skills/commission/SKILL.md +3 -3
- package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
- package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
- package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
- package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
- package/defaults/rules/decision-records.md +1 -1
- package/defaults/rules/meta-conventions.md +4 -4
- package/defaults/rules/mission-md.md +1 -1
- package/dist/agent-adapter/claude/adapter.d.ts +0 -6
- package/dist/agent-adapter/claude/adapter.js +0 -8
- package/dist/agent-adapter/claude/defaults.d.ts +10 -7
- package/dist/agent-adapter/claude/defaults.js +18 -16
- package/dist/agent-adapter/claude/hooks-builder.js +2 -2
- package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
- package/dist/agent-adapter/claude/spawn-args.js +20 -16
- package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
- package/dist/agent-adapter/claude/turn-machine.js +46 -5
- package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
- package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
- package/dist/agent-adapter/pi/mcp-bridge-logic.d.ts +11 -2
- package/dist/agent-adapter/pi/mcp-bridge-logic.js +32 -1
- package/dist/agent-adapter/pi/mcp-bridge.js +16 -15
- package/dist/agent-adapter/pi/session-options.d.ts +0 -6
- package/dist/agent-adapter/pi/session-options.js +1 -8
- package/dist/agent-adapter/types.d.ts +1 -1
- package/dist/core/mcp-tool-gate.d.ts +3 -17
- package/dist/core/mcp-tool-gate.js +4 -19
- package/dist/core/media-types.d.ts +10 -0
- package/dist/core/media-types.js +34 -0
- package/dist/core/platform-settings-spec.js +1 -1
- package/dist/core/settings-spec.d.ts +22 -1
- package/dist/core/settings-spec.js +33 -2
- package/dist/core/types/agent-types.d.ts +3 -1
- package/dist/core/utils.d.ts +1 -1
- package/dist/core/utils.js +1 -1
- package/dist/domain/agents/config.d.ts +1 -1
- package/dist/domain/agents/config.js +1 -1
- package/dist/domain/agents/profile-switch.d.ts +1 -1
- package/dist/domain/agents/profile-switch.js +3 -5
- package/dist/domain/agents/subagent/runner.js +0 -1
- package/dist/domain/commissions/commission-draft.d.ts +58 -0
- package/dist/domain/commissions/commission-draft.js +87 -4
- package/dist/domain/commissions/commission-finalize.d.ts +8 -3
- package/dist/domain/commissions/commission-finalize.js +14 -0
- package/dist/domain/executions/registry.d.ts +1 -2
- package/dist/domain/executions/registry.js +0 -3
- package/dist/domain/mcp/bundled-server.js +4 -3
- package/dist/domain/mcp/feishu/file.js +37 -18
- package/dist/domain/mcp/feishu/types.d.ts +3 -0
- package/dist/domain/mcp/feishu-server.js +1 -1
- package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
- package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
- package/dist/domain/mcp/tools/commission-tools.d.ts +12 -1
- package/dist/domain/mcp/tools/commission-tools.js +68 -14
- package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
- package/dist/domain/mcp/tools/remote-file.js +44 -0
- package/dist/domain/mcp/tools/slack.d.ts +2 -0
- package/dist/domain/mcp/tools/slack.js +22 -7
- package/dist/domain/mcp/tools/task-ops.js +5 -13
- package/dist/domain/mcp/tools/ui-file.js +23 -10
- package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
- package/dist/domain/mcp/tools/waitpoint.js +122 -0
- package/dist/domain/memory/agents-md-injector.d.ts +24 -0
- package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
- package/dist/domain/projects/project-store.d.ts +1 -1
- package/dist/domain/projects/project-store.js +3 -3
- package/dist/domain/remote/client-hot-reload.js +3 -1
- package/dist/domain/remote/client-manager.js +105 -126
- package/dist/domain/remote/client-ssh-tunnel.d.ts +16 -5
- package/dist/domain/remote/client-ssh-tunnel.js +12 -5
- package/dist/domain/remote/cortex-client-config.d.ts +1 -1
- package/dist/domain/remote/cortex-client-config.js +1 -1
- package/dist/domain/remote/device-file.d.ts +51 -0
- package/dist/domain/remote/device-file.js +193 -0
- package/dist/domain/remote/device-port.js +3 -0
- package/dist/domain/remote/reverse-stream.d.ts +18 -7
- package/dist/domain/remote/reverse-stream.js +19 -6
- package/dist/domain/runs/builders.js +0 -1
- package/dist/domain/runs/compact.js +0 -1
- package/dist/domain/runs/engine-spec.d.ts +11 -4
- package/dist/domain/runs/engine-spec.js +7 -4
- package/dist/domain/runs/prompt.js +16 -10
- package/dist/domain/runs/request.d.ts +0 -1
- package/dist/domain/sessions/session-hooks.d.ts +5 -12
- package/dist/domain/sessions/session-hooks.js +6 -13
- package/dist/domain/sessions/session-lifecycle.d.ts +4 -4
- package/dist/domain/sessions/session-lifecycle.js +5 -6
- package/dist/domain/sessions/session-retention.d.ts +1 -3
- package/dist/domain/sessions/session-retention.js +9 -26
- package/dist/domain/sessions/session-use.d.ts +32 -0
- package/dist/domain/sessions/session-use.js +63 -0
- package/dist/domain/sessions/session.js +6 -5
- package/dist/domain/system/server-update-check.js +29 -1
- package/dist/domain/system/update-ui-state.d.ts +32 -0
- package/dist/domain/system/update-ui-state.js +63 -0
- package/dist/domain/tasks/claim-recovery.js +2 -2
- package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
- package/dist/domain/tasks/dispatch-utils.js +46 -1
- package/dist/domain/tasks/dispatcher.js +4 -5
- package/dist/domain/tasks/mutator.d.ts +2 -2
- package/dist/domain/tasks/mutator.js +2 -2
- package/dist/domain/tasks/system/task-cli.js +2 -2
- package/dist/domain/tasks/system/task-state.js +1 -1
- package/dist/domain/threads/runner.js +3 -2
- package/dist/domain/ui-service/app-router.d.ts +54 -3
- package/dist/domain/ui-service/app-router.js +12 -14
- package/dist/domain/ui-service/input-schemas.d.ts +49 -5
- package/dist/domain/ui-service/input-schemas.js +35 -9
- package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
- package/dist/domain/ui-service/mutate/sessions.d.ts +17 -1
- package/dist/domain/ui-service/mutate/sessions.js +83 -3
- package/dist/domain/ui-service/mutate/system.d.ts +3 -1
- package/dist/domain/ui-service/mutate/system.js +13 -0
- package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
- package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
- package/dist/domain/ui-service/platform-settings.js +1 -1
- package/dist/domain/ui-service/plugins-shared.js +1 -1
- package/dist/domain/ui-service/query/config.js +1 -1
- package/dist/domain/ui-service/query/executions.js +0 -2
- package/dist/domain/ui-service/query/machine-detail.js +3 -8
- package/dist/domain/ui-service/query/memory.js +1 -1
- package/dist/domain/ui-service/query/sessions.js +7 -0
- package/dist/domain/ui-service/query/system.d.ts +2 -1
- package/dist/domain/ui-service/query/system.js +4 -0
- package/dist/domain/ui-service/query/threads.js +1 -54
- package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
- package/dist/domain/ui-service/query/waitpoints.js +117 -0
- package/dist/domain/ui-service/query-input-schemas.d.ts +3 -0
- package/dist/domain/ui-service/query-input-schemas.js +3 -0
- package/dist/domain/ui-service/trpc.js +1 -1
- package/dist/domain/ui-service/types.d.ts +175 -50
- package/dist/domain/ui-service/types.js +1 -1
- package/dist/domain/ui-service/ui-service.js +13 -33
- package/dist/domain/waitpoints/notices.d.ts +21 -0
- package/dist/domain/waitpoints/notices.js +115 -0
- package/dist/domain/waitpoints/service.d.ts +91 -0
- package/dist/domain/waitpoints/service.js +243 -0
- package/dist/entry/app.js +39 -29
- package/dist/entry/auth-login-cli.js +1 -1
- package/dist/entry/auth-login-terminal.js +1 -1
- package/dist/entry/init-auth.js +1 -1
- package/dist/entry/init.js +6 -6
- package/dist/entry/signal-cli.d.ts +30 -0
- package/dist/entry/signal-cli.js +207 -0
- package/dist/entry/start-ui-http.d.ts +1 -1
- package/dist/entry/start-ui-http.js +5 -3
- package/dist/events/event-types.d.ts +5 -7
- package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
- package/dist/hooks/cortex-hook-api.mjs +2 -2
- package/dist/hooks/new-session-hook.mjs +2 -2
- package/dist/hooks/rules-loader.mjs +2 -2
- package/dist/hooks/status-md-guard.mjs +8 -8
- package/dist/hooks/task-status-check.mjs +18 -76
- package/dist/hooks/tasks-yaml-guard.mjs +2 -2
- package/dist/orchestration/agent-file-send.d.ts +9 -0
- package/dist/orchestration/agent-file-send.js +21 -2
- package/dist/orchestration/agent-runner.d.ts +4 -3
- package/dist/orchestration/agent-runner.js +25 -23
- package/dist/orchestration/attachments-store.d.ts +31 -0
- package/dist/orchestration/attachments-store.js +184 -0
- package/dist/orchestration/conversation-request.d.ts +30 -8
- package/dist/orchestration/conversation-request.js +62 -26
- package/dist/orchestration/edit-retry.js +2 -1
- package/dist/orchestration/interactions/ask-user-resume.js +2 -1
- package/dist/orchestration/interactions/plan-approvals.js +1 -1
- package/dist/orchestration/interactions/ui-update-prompt.d.ts +8 -0
- package/dist/orchestration/interactions/ui-update-prompt.js +47 -0
- package/dist/orchestration/outputs-store.d.ts +11 -0
- package/dist/orchestration/outputs-store.js +32 -6
- package/dist/orchestration/resume-dispatcher.js +2 -2
- package/dist/orchestration/routing/file-handler.d.ts +23 -2
- package/dist/orchestration/routing/file-handler.js +22 -5
- package/dist/orchestration/routing/webhook.js +240 -39
- package/dist/orchestration/session-compact.d.ts +3 -0
- package/dist/orchestration/session-compact.js +3 -2
- package/dist/orchestration/session-events.d.ts +6 -0
- package/dist/orchestration/session-events.js +5 -0
- package/dist/orchestration/session-gateway.d.ts +1 -1
- package/dist/orchestration/session-gateway.js +1 -0
- package/dist/orchestration/thread-executor.d.ts +2 -0
- package/dist/orchestration/thread-executor.js +11 -1
- package/dist/orchestration/thread-input.d.ts +3 -2
- package/dist/orchestration/thread-input.js +8 -9
- package/dist/orchestration/turn/turn-prep.d.ts +15 -1
- package/dist/orchestration/turn/turn-prep.js +21 -9
- package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
- package/dist/orchestration/waitpoint-ingress.js +172 -0
- package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
- package/dist/orchestration/waitpoint-notifier.js +119 -0
- package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
- package/dist/orchestration/waitpoint-remote-drain.js +147 -0
- package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
- package/dist/orchestration/waitpoint-sweep.js +87 -0
- package/dist/platform/adapters/feishu-image.d.ts +19 -0
- package/dist/platform/adapters/feishu-image.js +71 -0
- package/dist/platform/adapters/feishu.d.ts +2 -0
- package/dist/platform/adapters/feishu.js +26 -16
- package/dist/platform/ui-http/app-update.d.ts +11 -0
- package/dist/platform/ui-http/app-update.js +3 -0
- package/dist/platform/ui-http/listening-ports.d.ts +1 -1
- package/dist/platform/ui-http/listening-ports.js +1 -1
- package/dist/platform/ui-http/ui-session.js +1 -1
- package/dist/store/conversation-ledger-repo.d.ts +10 -19
- package/dist/store/conversation-ledger-repo.js +143 -152
- package/dist/store/execution-repo.d.ts +1 -19
- package/dist/store/execution-repo.js +1 -18
- package/dist/store/project-notes-repo.js +11 -2
- package/dist/store/prompt-migration-replacements.js +1 -1
- package/dist/store/session-registry-import.d.ts +34 -0
- package/dist/store/session-registry-import.js +182 -0
- package/dist/store/session-registry-journal.d.ts +107 -0
- package/dist/store/session-registry-journal.js +308 -19
- package/dist/store/session-registry-repo.d.ts +113 -28
- package/dist/store/session-registry-repo.js +288 -105
- package/dist/store/version-migrations.d.ts +29 -3
- package/dist/store/version-migrations.js +288 -24
- package/dist/store/waitpoint-repo.d.ts +108 -0
- package/dist/store/waitpoint-repo.js +94 -0
- package/package.json +2 -2
- package/web/dist/assets/index-CwwQNMpP.css +1 -0
- package/web/dist/assets/index-DLSfgq3o.js +444 -0
- package/web/dist/assets/{index-aHbOZSP6.js → index-DZTuqUO4.js} +1 -1
- package/web/dist/index.html +2 -2
- package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
- package/dist/domain/executions/log-tailer.d.ts +0 -71
- package/dist/domain/executions/log-tailer.js +0 -194
- package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
- package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
- package/dist/domain/memory/cortex-md-scanner.js +0 -66
- package/dist/domain/remote/cortex-client.d.ts +0 -1
- package/dist/domain/remote/cortex-client.js +0 -662
- package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
- package/dist/domain/tasks/system/cortex-run.js +0 -360
- package/dist/store/session-repo.d.ts +0 -65
- package/dist/store/session-repo.js +0 -184
- package/web/dist/assets/index-BuXbCsuz.js +0 -444
- package/web/dist/assets/index-CCPxQ94C.css +0 -1
- /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
package/dist/entry/init-auth.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// input: auth snapshots, login CLI and terminal choices
|
|
2
2
|
// output: localized init authentication choices, usable backends and cancellation
|
|
3
3
|
// pos: Small shared init provider onboarding coordinator
|
|
4
|
-
// >>> Once I am updated, be sure to update my header comment and the parent folder
|
|
4
|
+
// >>> Once I am updated, be sure to update my header comment and the parent folder AGENTS.md <<<
|
|
5
5
|
import { defaultLoginDeps, LoginCliError, runAuthLoginCli } from './auth-login-cli.js';
|
|
6
6
|
import { t } from '../core/i18n.js';
|
|
7
7
|
export function usableBackends(snapshot) {
|
package/dist/entry/init.js
CHANGED
|
@@ -1166,15 +1166,15 @@ function safeCopyDir(srcDir, dstDir, force) {
|
|
|
1166
1166
|
// ─── Config copy & generation ──────────────────────────────────
|
|
1167
1167
|
function copyDefaults(paths, force) {
|
|
1168
1168
|
// Scaffold files — never overwrite (user-customized content)
|
|
1169
|
-
safeCopy(path.join(DEFAULTS_DIR, '
|
|
1169
|
+
safeCopy(path.join(DEFAULTS_DIR, 'AGENTS.md'), path.join(paths.DATA_DIR, 'AGENTS.md'), false, 'AGENTS.md');
|
|
1170
1170
|
safeCopy(path.join(DEFAULTS_DIR, 'gitignore'), path.join(paths.DATA_DIR, '.gitignore'), false, '.gitignore');
|
|
1171
1171
|
safeCopy(path.join(DEFAULTS_DIR, '.claude', 'settings.json'), path.join(paths.DATA_DIR, '.claude', 'settings.json'), false, '.claude/settings.json');
|
|
1172
1172
|
// Context scaffold files — never overwrite
|
|
1173
|
-
safeCopy(path.join(DEFAULTS_DIR, 'context', '
|
|
1174
|
-
safeCopy(path.join(DEFAULTS_DIR, 'context', 'projects', '
|
|
1175
|
-
safeCopy(path.join(DEFAULTS_DIR, 'context', 'scans', '
|
|
1176
|
-
safeCopy(path.join(DEFAULTS_DIR, 'context', 'ideas', '
|
|
1177
|
-
safeCopy(path.join(DEFAULTS_DIR, 'context', 'user', '
|
|
1173
|
+
safeCopy(path.join(DEFAULTS_DIR, 'context', 'AGENTS.md'), path.join(paths.CONTEXT_DIR, 'AGENTS.md'), false, 'context/AGENTS.md');
|
|
1174
|
+
safeCopy(path.join(DEFAULTS_DIR, 'context', 'projects', 'AGENTS.md'), path.join(paths.PROJECTS_DIR, 'AGENTS.md'), false, 'context/projects/AGENTS.md');
|
|
1175
|
+
safeCopy(path.join(DEFAULTS_DIR, 'context', 'scans', 'AGENTS.md'), path.join(paths.CONTEXT_DIR, 'scans', 'AGENTS.md'), false, 'context/scans/AGENTS.md');
|
|
1176
|
+
safeCopy(path.join(DEFAULTS_DIR, 'context', 'ideas', 'AGENTS.md'), path.join(paths.CONTEXT_DIR, 'ideas', 'AGENTS.md'), false, 'context/ideas/AGENTS.md');
|
|
1177
|
+
safeCopy(path.join(DEFAULTS_DIR, 'context', 'user', 'AGENTS.md'), path.join(paths.CONTEXT_DIR, 'user', 'AGENTS.md'), false, 'context/user/AGENTS.md');
|
|
1178
1178
|
// Config defaults — budget overwrites only with --force;
|
|
1179
1179
|
// thread-templates are merged per-file (new agents/templates/shells added, existing preserved)
|
|
1180
1180
|
safeCopy(path.join(DEFAULTS_DIR, 'config', 'budget.json'), path.join(paths.CONFIG_DIR, 'budget.json'), force, 'budget.json');
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export interface SignalCliResult {
|
|
2
|
+
exitCode: number;
|
|
3
|
+
stdout: string;
|
|
4
|
+
stderr: string;
|
|
5
|
+
}
|
|
6
|
+
interface ParsedArgs {
|
|
7
|
+
help: boolean;
|
|
8
|
+
id: string | null;
|
|
9
|
+
secret: string | null;
|
|
10
|
+
status: string | null;
|
|
11
|
+
message: string | null;
|
|
12
|
+
data: string | null;
|
|
13
|
+
member: string | null;
|
|
14
|
+
exitCode: string | null;
|
|
15
|
+
url: string | null;
|
|
16
|
+
noSpool: boolean;
|
|
17
|
+
}
|
|
18
|
+
export interface SignalCliOptions {
|
|
19
|
+
env?: NodeJS.ProcessEnv;
|
|
20
|
+
post?: (url: string, body: unknown) => Promise<{
|
|
21
|
+
status: number;
|
|
22
|
+
body: any;
|
|
23
|
+
}>;
|
|
24
|
+
spoolDir?: string;
|
|
25
|
+
writeSpool?: (dir: string, name: string, contents: string) => void;
|
|
26
|
+
}
|
|
27
|
+
export declare function parseSignalArgs(argv: string[]): ParsedArgs;
|
|
28
|
+
export declare function runSignalCli(argv: string[], options?: SignalCliOptions): Promise<SignalCliResult>;
|
|
29
|
+
export declare function main(argv?: string[]): Promise<void>;
|
|
30
|
+
export {};
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// input: argv, CORTEX_SIGNAL_ID / CORTEX_SIGNAL_SECRET, WEBHOOK_PORT
|
|
3
|
+
// output: cortex-signal binary — resolve a waitpoint from outside Cortex
|
|
4
|
+
// pos: The emitter half of the waitpoint feature. Deliberately does not launch, supervise or
|
|
5
|
+
// adopt anything: the caller starts their own process however they like and appends one
|
|
6
|
+
// line. If the daemon cannot be reached the signal is spooled to disk instead of lost,
|
|
7
|
+
// which is the same file the daemon (or a device drain) picks up later.
|
|
8
|
+
import * as fs from 'node:fs';
|
|
9
|
+
import * as os from 'node:os';
|
|
10
|
+
import * as path from 'node:path';
|
|
11
|
+
import { formatError, formatHelp, cliError, readStdinSync } from '../core/cli-utils.js';
|
|
12
|
+
import { isMainModule } from '../core/utils.js';
|
|
13
|
+
const HELP = {
|
|
14
|
+
name: 'cortex-signal',
|
|
15
|
+
description: 'Tell Cortex that something it is waiting for has finished.',
|
|
16
|
+
usage: 'cortex-signal [--id wp_…] [--secret …] [--status ok|fail|progress] [--message TEXT] [--exit-code N]',
|
|
17
|
+
options: [
|
|
18
|
+
{ flag: '--id <wp_…>', description: 'Waitpoint id', default: '$CORTEX_SIGNAL_ID' },
|
|
19
|
+
{ flag: '--secret <hex>', description: 'Capability issued with the waitpoint', default: '$CORTEX_SIGNAL_SECRET' },
|
|
20
|
+
{ flag: '--status <s>', description: 'ok | fail | progress', default: 'ok' },
|
|
21
|
+
{ flag: '--exit-code <n>', description: 'Set status from a command exit code (0 = ok, else fail)' },
|
|
22
|
+
{ flag: '--message <text>', description: 'One-line summary shown in the wake message' },
|
|
23
|
+
{ flag: '--member <name>', description: 'Which member of a multi-job waitpoint this is' },
|
|
24
|
+
{ flag: '--data <@file|->', description: 'Extra payload from a file or stdin (treated as data, not instructions)' },
|
|
25
|
+
{ flag: '--url <url>', description: 'Daemon signal endpoint', default: 'http://127.0.0.1:$WEBHOOK_PORT/webhook/signal' },
|
|
26
|
+
{ flag: '--no-spool', description: 'Fail instead of spooling to disk when the daemon is unreachable' },
|
|
27
|
+
{ flag: '--help, -h', description: 'Show this help' },
|
|
28
|
+
],
|
|
29
|
+
examples: [
|
|
30
|
+
{ description: 'Report the exit code of the command that just ran', command: 'python train.py; cortex-signal --exit-code $?' },
|
|
31
|
+
{ description: 'Report one arm of a multi-job waitpoint', command: 'cortex-signal --member arm2 --status ok --message "33,120 steps"' },
|
|
32
|
+
{ description: 'Attach the tail of a log as data', command: 'tail -c 2000 train.log | cortex-signal --exit-code $? --data -' },
|
|
33
|
+
],
|
|
34
|
+
};
|
|
35
|
+
const VALUE_FLAGS = {
|
|
36
|
+
'--id': 'id',
|
|
37
|
+
'--secret': 'secret',
|
|
38
|
+
'--status': 'status',
|
|
39
|
+
'--message': 'message',
|
|
40
|
+
'--member': 'member',
|
|
41
|
+
'--data': 'data',
|
|
42
|
+
'--exit-code': 'exitCode',
|
|
43
|
+
'--url': 'url',
|
|
44
|
+
};
|
|
45
|
+
const STATUSES = ['ok', 'fail', 'progress'];
|
|
46
|
+
export function parseSignalArgs(argv) {
|
|
47
|
+
const parsed = {
|
|
48
|
+
help: false, id: null, secret: null, status: null, message: null,
|
|
49
|
+
data: null, member: null, exitCode: null, url: null, noSpool: false,
|
|
50
|
+
};
|
|
51
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
52
|
+
const token = argv[i];
|
|
53
|
+
if (token === '--help' || token === '-h') {
|
|
54
|
+
parsed.help = true;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (token === '--no-spool') {
|
|
58
|
+
parsed.noSpool = true;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const field = VALUE_FLAGS[token];
|
|
62
|
+
if (!field) {
|
|
63
|
+
throw cliError(formatError(`Unknown argument: '${token}'`, {
|
|
64
|
+
validValues: [...Object.keys(VALUE_FLAGS), '--no-spool', '--help'],
|
|
65
|
+
}));
|
|
66
|
+
}
|
|
67
|
+
const value = argv[i + 1];
|
|
68
|
+
if (value === undefined || (value.startsWith('--') && field !== 'message')) {
|
|
69
|
+
throw cliError(formatError(`${token} requires a value`));
|
|
70
|
+
}
|
|
71
|
+
parsed[field] = value;
|
|
72
|
+
i += 1;
|
|
73
|
+
}
|
|
74
|
+
return parsed;
|
|
75
|
+
}
|
|
76
|
+
/** `--exit-code` is the ergonomic form: one flag turns `$?` into both a status and a message. */
|
|
77
|
+
function resolveStatus(parsed) {
|
|
78
|
+
if (parsed.exitCode !== null) {
|
|
79
|
+
const code = Number.parseInt(parsed.exitCode, 10);
|
|
80
|
+
if (!Number.isFinite(code)) {
|
|
81
|
+
throw cliError(formatError(`--exit-code must be a number, got '${parsed.exitCode}'`));
|
|
82
|
+
}
|
|
83
|
+
const status = parsed.status ?? (code === 0 ? 'ok' : 'fail');
|
|
84
|
+
return { status, message: parsed.message ?? `exit=${code}` };
|
|
85
|
+
}
|
|
86
|
+
const status = parsed.status ?? 'ok';
|
|
87
|
+
if (!STATUSES.includes(status)) {
|
|
88
|
+
throw cliError(formatError(`Invalid --status '${status}'`, { validValues: STATUSES }));
|
|
89
|
+
}
|
|
90
|
+
return { status, message: parsed.message };
|
|
91
|
+
}
|
|
92
|
+
function readData(spec) {
|
|
93
|
+
if (spec === null)
|
|
94
|
+
return undefined;
|
|
95
|
+
if (spec === '-')
|
|
96
|
+
return readStdinSync();
|
|
97
|
+
if (spec.startsWith('@')) {
|
|
98
|
+
const file = spec.slice(1);
|
|
99
|
+
try {
|
|
100
|
+
return fs.readFileSync(file, 'utf8');
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
throw cliError(formatError(`Cannot read --data file '${file}': ${error.message}`));
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return spec;
|
|
107
|
+
}
|
|
108
|
+
async function httpPost(url, body) {
|
|
109
|
+
const response = await fetch(url, {
|
|
110
|
+
method: 'POST',
|
|
111
|
+
headers: { 'content-type': 'application/json' },
|
|
112
|
+
body: JSON.stringify(body),
|
|
113
|
+
});
|
|
114
|
+
const text = await response.text();
|
|
115
|
+
let parsed = text;
|
|
116
|
+
try {
|
|
117
|
+
parsed = JSON.parse(text);
|
|
118
|
+
}
|
|
119
|
+
catch { /* non-JSON bodies surface as text */ }
|
|
120
|
+
return { status: response.status, body: parsed };
|
|
121
|
+
}
|
|
122
|
+
function defaultSpoolDir(env) {
|
|
123
|
+
const home = env.CORTEX_HOME ? path.resolve(env.CORTEX_HOME) : path.join(os.homedir(), '.cortex');
|
|
124
|
+
return path.join(home, 'tmp', 'signals');
|
|
125
|
+
}
|
|
126
|
+
/** Write-then-rename: a same-directory rename is atomic, so a drain never sees a half file. */
|
|
127
|
+
function writeSpoolFile(dir, name, contents) {
|
|
128
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
129
|
+
const tmp = path.join(dir, `${name}.tmp`);
|
|
130
|
+
fs.writeFileSync(tmp, contents);
|
|
131
|
+
fs.renameSync(tmp, path.join(dir, name));
|
|
132
|
+
}
|
|
133
|
+
export async function runSignalCli(argv, options = {}) {
|
|
134
|
+
const env = options.env ?? process.env;
|
|
135
|
+
try {
|
|
136
|
+
const parsed = parseSignalArgs(argv);
|
|
137
|
+
if (parsed.help || argv.length === 0) {
|
|
138
|
+
return { exitCode: 0, stdout: formatHelp(HELP), stderr: '' };
|
|
139
|
+
}
|
|
140
|
+
const id = parsed.id ?? env.CORTEX_SIGNAL_ID ?? null;
|
|
141
|
+
const secret = parsed.secret ?? env.CORTEX_SIGNAL_SECRET ?? null;
|
|
142
|
+
if (!id || !secret) {
|
|
143
|
+
return {
|
|
144
|
+
exitCode: 2,
|
|
145
|
+
stdout: '',
|
|
146
|
+
stderr: formatError('A waitpoint id and secret are required', {
|
|
147
|
+
hint: 'Pass --id/--secret, or export CORTEX_SIGNAL_ID and CORTEX_SIGNAL_SECRET (wait_create prints both).',
|
|
148
|
+
}),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
const { status, message } = resolveStatus(parsed);
|
|
152
|
+
const payload = { id, secret, status };
|
|
153
|
+
if (message)
|
|
154
|
+
payload.message = message;
|
|
155
|
+
if (parsed.member)
|
|
156
|
+
payload.member = parsed.member;
|
|
157
|
+
const data = readData(parsed.data);
|
|
158
|
+
if (data !== undefined)
|
|
159
|
+
payload.data = data;
|
|
160
|
+
const port = env.WEBHOOK_PORT || '3001';
|
|
161
|
+
const url = parsed.url ?? `http://127.0.0.1:${port}/webhook/signal`;
|
|
162
|
+
const post = options.post ?? httpPost;
|
|
163
|
+
let response;
|
|
164
|
+
try {
|
|
165
|
+
response = await post(url, payload);
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
// The daemon is down, or this machine has no route to it. Spooling is not a fallback for
|
|
169
|
+
// failure — it is the normal path on a remote device, where the daemon collects the file.
|
|
170
|
+
if (parsed.noSpool) {
|
|
171
|
+
return { exitCode: 1, stdout: '', stderr: formatError(`Cannot reach ${url}: ${error.message}`) };
|
|
172
|
+
}
|
|
173
|
+
const dir = options.spoolDir ?? defaultSpoolDir(env);
|
|
174
|
+
const name = `${Date.now()}-${process.pid}-${Math.random().toString(36).slice(2, 8)}.json`;
|
|
175
|
+
(options.writeSpool ?? writeSpoolFile)(dir, name, JSON.stringify(payload));
|
|
176
|
+
return { exitCode: 0, stdout: `spooled ${path.join(dir, name)}`, stderr: '' };
|
|
177
|
+
}
|
|
178
|
+
if (response.status === 202) {
|
|
179
|
+
const fired = response.body?.fired ? ' (waitpoint fired)' : '';
|
|
180
|
+
return { exitCode: 0, stdout: `accepted${fired}`, stderr: '' };
|
|
181
|
+
}
|
|
182
|
+
if (response.status === 410) {
|
|
183
|
+
// Not an error worth failing a build over: the waitpoint did its job already.
|
|
184
|
+
return { exitCode: 0, stdout: `already resolved (${response.body?.state ?? 'unknown'})`, stderr: '' };
|
|
185
|
+
}
|
|
186
|
+
const detail = typeof response.body === 'object' && response.body?.error ? response.body.error : String(response.body ?? '');
|
|
187
|
+
return { exitCode: 1, stdout: '', stderr: formatError(`Signal refused (HTTP ${response.status}): ${detail}`) };
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
// cliError() tags usage problems with cliMessage; exit 2 is the usage code (CLI Rule ④).
|
|
191
|
+
const cliMessage = error.cliMessage;
|
|
192
|
+
if (cliMessage)
|
|
193
|
+
return { exitCode: 2, stdout: '', stderr: cliMessage };
|
|
194
|
+
return { exitCode: 1, stdout: '', stderr: error.message };
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
198
|
+
const result = await runSignalCli(argv);
|
|
199
|
+
if (result.stdout)
|
|
200
|
+
process.stdout.write(`${result.stdout}\n`);
|
|
201
|
+
if (result.stderr)
|
|
202
|
+
process.stderr.write(`${result.stderr}\n`);
|
|
203
|
+
process.exitCode = result.exitCode;
|
|
204
|
+
}
|
|
205
|
+
if (isMainModule(import.meta.url)) {
|
|
206
|
+
void main();
|
|
207
|
+
}
|
|
@@ -25,7 +25,7 @@ export interface StartUiHttpOptions {
|
|
|
25
25
|
verifyAccessJwt?: AccessJwtVerifier;
|
|
26
26
|
/**
|
|
27
27
|
* Explicit session store for the browser token-login path. Production builds one backed by
|
|
28
|
-
*
|
|
28
|
+
* STORE_DIR/ui-sessions.json; tests inject a memory-only store so they never touch the real file.
|
|
29
29
|
* Ignored when CORTEX_UI_TOKEN_LOGIN is switched off.
|
|
30
30
|
*/
|
|
31
31
|
sessionStore?: UiSessionStore;
|
|
@@ -9,6 +9,7 @@ import { createUiSessionStore, DEFAULT_SESSION_TTL_MS } from '../platform/ui-htt
|
|
|
9
9
|
import { createUiAuthRoutes, createUiSessionProbeRoute, UI_LOGIN_PATH, UI_SESSION_PATH, } from '../platform/ui-http/ui-auth-routes.js';
|
|
10
10
|
import { createOtaRoutes } from '../platform/ui-http/ui-ota.js';
|
|
11
11
|
import { createAppUpdateRoutes } from '../platform/ui-http/app-update.js';
|
|
12
|
+
import { isUpdateDevMode } from '../domain/system/server-update-check.js';
|
|
12
13
|
import { createForwardRoutes } from '../platform/ui-http/port-forward.js';
|
|
13
14
|
import { createBrowserStatusRoutes } from '../platform/ui-http/browser-status.js';
|
|
14
15
|
import { createDevicePortRoutes } from '../platform/ui-http/device-ports.js';
|
|
@@ -18,7 +19,7 @@ import { accessVerifierFromEnv } from '../platform/ui-http/access-jwt.js';
|
|
|
18
19
|
import { getClientToken } from '../core/auth.js';
|
|
19
20
|
import { createLogger } from '../core/log.js';
|
|
20
21
|
import { getSettings } from '../core/settings.js';
|
|
21
|
-
import { WORKSPACE_DIR,
|
|
22
|
+
import { WORKSPACE_DIR, STORE_DIR, resolveWorkspaceRelPath } from '../core/paths.js';
|
|
22
23
|
import { projectStore } from '../domain/projects/project-store.js';
|
|
23
24
|
import { resolveMemoryFilePath } from '../domain/ui-service/query/memory.js';
|
|
24
25
|
const log = createLogger('ui-http');
|
|
@@ -30,7 +31,7 @@ function isEnabled(env) {
|
|
|
30
31
|
return v === '1' || v === 'true' || v === 'on' || v === 'yes';
|
|
31
32
|
}
|
|
32
33
|
/** Where browser sessions survive a daemon restart. Written 0600 by the store. */
|
|
33
|
-
const SESSIONS_FILE = path.join(
|
|
34
|
+
const SESSIONS_FILE = path.join(STORE_DIR, 'ui-sessions.json');
|
|
34
35
|
/**
|
|
35
36
|
* Token login is ON unless explicitly switched off — a browser reaching this server can log in by
|
|
36
37
|
* pasting the clientToken once. Opting out (`CORTEX_UI_TOKEN_LOGIN=0`) removes the login routes and
|
|
@@ -393,7 +394,8 @@ export function startUiHttpServer(opts) {
|
|
|
393
394
|
// App shell self-update: advertises the newest GitHub release carrying native app assets
|
|
394
395
|
// (capped at this server's version) so the shell can offer a one-prompt update. JSON only —
|
|
395
396
|
// the binaries download straight from the GitHub CDN. Same auth gate as tRPC.
|
|
396
|
-
|
|
397
|
+
// A dev server never advertises app releases: see AppUpdateRouteOptions.devMode.
|
|
398
|
+
...createAppUpdateRoutes({ devMode: isUpdateDevMode() }),
|
|
397
399
|
// Listening-port discovery for the desktop port forward: tells the shell which loopback
|
|
398
400
|
// services exist here so the Ports list can offer them. Same auth gate as tRPC.
|
|
399
401
|
...createForwardRoutes(),
|
|
@@ -120,6 +120,11 @@ export type CortexEvent = {
|
|
|
120
120
|
ts: string;
|
|
121
121
|
sessionId: string;
|
|
122
122
|
channel: string;
|
|
123
|
+
} | {
|
|
124
|
+
type: 'session.commission';
|
|
125
|
+
ts: string;
|
|
126
|
+
sessionId: string;
|
|
127
|
+
channel: string;
|
|
123
128
|
} | {
|
|
124
129
|
type: 'plan.submitted';
|
|
125
130
|
ts: string;
|
|
@@ -185,13 +190,6 @@ export type CortexEvent = {
|
|
|
185
190
|
ts: string;
|
|
186
191
|
executionId: string;
|
|
187
192
|
reason: string;
|
|
188
|
-
} | {
|
|
189
|
-
type: 'execution.log';
|
|
190
|
-
ts: string;
|
|
191
|
-
executionId: string;
|
|
192
|
-
seq: number;
|
|
193
|
-
lines: string[];
|
|
194
|
-
dropped?: number;
|
|
195
193
|
} | {
|
|
196
194
|
type: 'auth.required';
|
|
197
195
|
ts: string;
|
|
@@ -1,33 +1,45 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// @cortex-hook-version 2026.
|
|
2
|
+
// @cortex-hook-version 2026.9.15 ← set to the current release version (agent-server/package.json) whenever you change this hook; syncManagedHooks then refreshes deployed installs
|
|
3
3
|
// input: stdin JSON — Claude Code hook event or PI hook-bridge payload; or runHook(payload, env)
|
|
4
4
|
// output: { hookSpecificOutput: { hookEventName, additionalContext, matched } }
|
|
5
5
|
// Exported `runHook` is the in-process entry point: the PI hook bridge calls it directly
|
|
6
6
|
// instead of spawning this file, so every path here takes its scope from the `env`
|
|
7
7
|
// argument rather than process.env (one daemon process serves many sessions).
|
|
8
|
-
// pos: Inject
|
|
8
|
+
// pos: Inject the AGENTS.md / AGENTS.local.md ancestor chain that THE BACKEND DOES NOT LOAD.
|
|
9
|
+
// Both backends load AGENTS.md natively now, so this hook only covers their blind spots
|
|
10
|
+
// (see backendLoadsNatively below for the measured matrix):
|
|
11
|
+
// · paths outside the session cwd tree — neither backend loads these
|
|
12
|
+
// · AGENTS.local.md, anywhere — neither backend has a `.local` name
|
|
13
|
+
// · descendants of cwd, on PI — PI walks cwd→root only, never downward
|
|
14
|
+
// Anything the backend already loaded is recorded in the dedup cache WITHOUT being
|
|
15
|
+
// injected, so the agent never receives the same rules twice.
|
|
9
16
|
// 2-event dispatch:
|
|
10
17
|
// PostToolUse (Read|Edit) — from tool_input.file_path/path
|
|
11
18
|
// SessionStart (startup|resume|clear|compact) — from payload.cwd
|
|
12
19
|
// Shared per-session cache with remote MCP injection under tmp/cortexmd-cache
|
|
13
20
|
// — stable session + physical host + path + mtime dedup across tool families
|
|
14
21
|
// — only files actually injected are marked seen; truncated files stay eligible
|
|
15
|
-
// markOnlyPaths: exact
|
|
22
|
+
// markOnlyPaths: exact AGENTS.md tool target → cache update only, no duplicate
|
|
16
23
|
// Total length guard at 9,500 chars; files that overflow the budget are turned into an
|
|
17
24
|
// explicit "Read EACH of these files now" instruction instead of a silent drop
|
|
18
|
-
// >>> If I am updated, be sure to update my header comment and the
|
|
25
|
+
// >>> If I am updated, be sure to update my header comment and the AGENTS.md in the same folder <<<
|
|
19
26
|
|
|
20
27
|
import {
|
|
21
28
|
closeSync, existsSync, mkdirSync, openSync, readFileSync,
|
|
22
29
|
renameSync, rmSync, statSync, writeFileSync,
|
|
23
30
|
} from 'fs';
|
|
24
|
-
import { join, resolve, dirname, basename } from 'path';
|
|
31
|
+
import { join, resolve, dirname, basename, sep } from 'path';
|
|
25
32
|
import { homedir, hostname } from 'os';
|
|
26
33
|
import { fileURLToPath } from 'url';
|
|
27
34
|
|
|
28
35
|
const HOSTNAME = hostname();
|
|
29
36
|
const HOST_ID = HOSTNAME.toLowerCase();
|
|
30
|
-
const
|
|
37
|
+
const AGENTS_MD_NAMES = ['AGENTS.md', 'AGENTS.local.md'];
|
|
38
|
+
/** Names neither backend loads on its own — always ours to inject. */
|
|
39
|
+
const LOCAL_ONLY_NAMES = new Set(['AGENTS.local.md']);
|
|
40
|
+
/** Claude's AGENTS.md fallback is all-or-nothing: a single CLAUDE.md anywhere in the cwd
|
|
41
|
+
* ancestor chain makes it load THAT family and ignore every AGENTS.md. */
|
|
42
|
+
const CLAUDE_MD_NAMES = ['CLAUDE.md', 'CLAUDE.local.md', join('.claude', 'CLAUDE.md')];
|
|
31
43
|
const MAX_FILE_SIZE = 200 * 1024;
|
|
32
44
|
const MAX_DEPTH = 20;
|
|
33
45
|
const MAX_CONTEXT_CHARS = 9500;
|
|
@@ -40,7 +52,7 @@ const SESSION_ID_RE = /^[A-Za-z0-9._-]+$/;
|
|
|
40
52
|
function hookPaths(env) {
|
|
41
53
|
const home = env.CORTEX_HOME ? resolve(env.CORTEX_HOME) : join(homedir(), '.cortex');
|
|
42
54
|
return {
|
|
43
|
-
homeFallback: join(home, '
|
|
55
|
+
homeFallback: join(home, 'AGENTS.md'),
|
|
44
56
|
cacheDir: join(home, 'tmp', 'cortexmd-cache'),
|
|
45
57
|
};
|
|
46
58
|
}
|
|
@@ -59,32 +71,34 @@ function tryReadEntry(filePath) {
|
|
|
59
71
|
}
|
|
60
72
|
}
|
|
61
73
|
|
|
74
|
+
/** The directory an ancestor walk should start from: the path itself when it is a directory,
|
|
75
|
+
* otherwise its parent (also the right answer for a path that does not exist). */
|
|
76
|
+
function startDir(targetFilePath) {
|
|
77
|
+
const resolved = resolve(targetFilePath);
|
|
78
|
+
try {
|
|
79
|
+
const st = statSync(resolved, { throwIfNoEntry: false });
|
|
80
|
+
return (st && st.isDirectory()) ? resolved : dirname(resolved);
|
|
81
|
+
} catch {
|
|
82
|
+
return dirname(resolved);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
62
86
|
/** Walk from the directory containing `targetFilePath` up to the filesystem root,
|
|
63
|
-
* collecting
|
|
64
|
-
* home fallback at ~/.cortex/
|
|
65
|
-
* If targetFilePath is a directory, scan that directory and its ancestors.
|
|
66
|
-
* If it is a file (or does not exist), scan its parent directory and ancestors. */
|
|
87
|
+
* collecting AGENTS.md and AGENTS.local.md at each level. Also appends the
|
|
88
|
+
* home fallback at ~/.cortex/AGENTS.md if present. Returns leaf→root order. */
|
|
67
89
|
function scanChain(targetFilePath, paths) {
|
|
68
90
|
const entries = [];
|
|
69
91
|
const seen = new Set();
|
|
70
92
|
|
|
71
|
-
let resolved;
|
|
72
|
-
try {
|
|
73
|
-
resolved = resolve(targetFilePath);
|
|
74
|
-
} catch {
|
|
75
|
-
return entries;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
93
|
let dir;
|
|
79
94
|
try {
|
|
80
|
-
|
|
81
|
-
dir = (st && st.isDirectory()) ? resolved : dirname(resolved);
|
|
95
|
+
dir = startDir(targetFilePath);
|
|
82
96
|
} catch {
|
|
83
|
-
|
|
97
|
+
return entries;
|
|
84
98
|
}
|
|
85
99
|
|
|
86
100
|
for (let depth = 0; depth < MAX_DEPTH; depth++) {
|
|
87
|
-
for (const name of
|
|
101
|
+
for (const name of AGENTS_MD_NAMES) {
|
|
88
102
|
const p = join(dir, name);
|
|
89
103
|
if (seen.has(p)) continue;
|
|
90
104
|
seen.add(p);
|
|
@@ -106,6 +120,66 @@ function scanChain(targetFilePath, paths) {
|
|
|
106
120
|
return entries;
|
|
107
121
|
}
|
|
108
122
|
|
|
123
|
+
// ── backend coverage ──
|
|
124
|
+
//
|
|
125
|
+
// Measured against Claude Code 2.1.278 and pi (@earendil-works/pi-coding-agent):
|
|
126
|
+
//
|
|
127
|
+
// memory file location | Claude | PI | ours?
|
|
128
|
+
// --------------------------------+--------+-----+-------
|
|
129
|
+
// ancestor of cwd (incl. cwd) | yes | yes | no
|
|
130
|
+
// descendant of cwd, read by tool | yes | no | PI only
|
|
131
|
+
// outside the cwd tree | no | no | both
|
|
132
|
+
// *.local.md, anywhere | no | no | both
|
|
133
|
+
//
|
|
134
|
+
// Claude resolves its fallback through the `claude-md-or-agents-md` setting, whose default
|
|
135
|
+
// loads AGENTS.md ONLY when no CLAUDE.md exists in the chain — hence the guard below. PI
|
|
136
|
+
// reads ["AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"] per directory, cwd→root, and never
|
|
137
|
+
// descends, so on PI this hook is the only thing that delivers a project's own index file.
|
|
138
|
+
|
|
139
|
+
/** True when a CLAUDE.md-family file sits in the cwd ancestor chain, which switches Claude off
|
|
140
|
+
* the AGENTS.md fallback entirely. Cheap: same walk shape as scanChain, existence checks only. */
|
|
141
|
+
function claudeMdInChain(cwd) {
|
|
142
|
+
let dir;
|
|
143
|
+
try {
|
|
144
|
+
dir = startDir(cwd);
|
|
145
|
+
} catch {
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
for (let depth = 0; depth < MAX_DEPTH; depth++) {
|
|
149
|
+
for (const name of CLAUDE_MD_NAMES) {
|
|
150
|
+
try {
|
|
151
|
+
if (existsSync(join(dir, name))) return true;
|
|
152
|
+
} catch { /* unreadable — treat as absent */ }
|
|
153
|
+
}
|
|
154
|
+
const parent = dirname(dir);
|
|
155
|
+
if (parent === dir) break;
|
|
156
|
+
dir = parent;
|
|
157
|
+
}
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function isAncestorOrSelf(dir, cwd) {
|
|
162
|
+
return dir === cwd || cwd.startsWith(dir.endsWith(sep) ? dir : dir + sep);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function isUnder(dir, cwd) {
|
|
166
|
+
return dir === cwd || dir.startsWith(cwd.endsWith(sep) ? cwd : cwd + sep);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Whether the backend has already put this entry in the agent's context on its own.
|
|
171
|
+
* Such entries are marked in the dedup cache but never injected — that is the whole point of
|
|
172
|
+
* this hook after both backends gained native AGENTS.md support.
|
|
173
|
+
*/
|
|
174
|
+
function backendLoadsNatively(entry, cwd, backend, claudeUsesAgentsMd) {
|
|
175
|
+
if (LOCAL_ONLY_NAMES.has(basename(entry.path))) return false;
|
|
176
|
+
if (!cwd) return false;
|
|
177
|
+
const dir = dirname(entry.path);
|
|
178
|
+
if (backend === 'pi') return isAncestorOrSelf(dir, cwd);
|
|
179
|
+
if (!claudeUsesAgentsMd) return false;
|
|
180
|
+
return isAncestorOrSelf(dir, cwd) || isUnder(dir, cwd);
|
|
181
|
+
}
|
|
182
|
+
|
|
109
183
|
// ── cache helpers ──
|
|
110
184
|
|
|
111
185
|
function loadCache(sessionId, paths) {
|
|
@@ -186,7 +260,7 @@ function buildContext(entries) {
|
|
|
186
260
|
// Walk entries in original order (leaf→root), inlining each as a block until the char
|
|
187
261
|
// budget is exhausted. Once exhausted, the remaining entries are NOT inlined — instead
|
|
188
262
|
// they are turned into an explicit read-instruction below, so their rules are never
|
|
189
|
-
// silently dropped (e.g. a root-level
|
|
263
|
+
// silently dropped (e.g. a root-level AGENTS.local.md carrying dev/safety rules).
|
|
190
264
|
const includedBlocks = [];
|
|
191
265
|
const includedPaths = [];
|
|
192
266
|
const truncated = [];
|
|
@@ -194,7 +268,7 @@ function buildContext(entries) {
|
|
|
194
268
|
let budgetExhausted = false;
|
|
195
269
|
|
|
196
270
|
for (const e of entries) {
|
|
197
|
-
const block = `<system-reminder>\nAuto-loaded
|
|
271
|
+
const block = `<system-reminder>\nAuto-loaded AGENTS.md from ${HOSTNAME}:${e.path} (ancestor of accessed path, outside the session working directory). These instructions apply to files under this directory.\n\n${e.content}\n</system-reminder>`;
|
|
198
272
|
if (budgetExhausted || totalLen + block.length > MAX_CONTEXT_CHARS) {
|
|
199
273
|
budgetExhausted = true; // match prior behavior: stop inlining at the first overflow
|
|
200
274
|
truncated.push(e);
|
|
@@ -212,7 +286,7 @@ function buildContext(entries) {
|
|
|
212
286
|
if (truncated.length > 0) {
|
|
213
287
|
const list = truncated.map(e => `- ${e.path}`).join('\n');
|
|
214
288
|
parts.push(
|
|
215
|
-
`<system-reminder>\n⚠️ ${truncated.length}
|
|
289
|
+
`<system-reminder>\n⚠️ ${truncated.length} AGENTS rule file(s) were too large to inline here. ` +
|
|
216
290
|
`Read EACH of the following files now to load their rules before proceeding:\n${list}\n</system-reminder>`
|
|
217
291
|
);
|
|
218
292
|
}
|
|
@@ -227,6 +301,10 @@ function buildContext(entries) {
|
|
|
227
301
|
* Run the hook against one payload and one session environment.
|
|
228
302
|
* Returns the hook output object, or null when this event injects nothing.
|
|
229
303
|
* Pure of process state apart from the filesystem, so the PI bridge can call it in-process.
|
|
304
|
+
*
|
|
305
|
+
* SessionStart is deliberately mark-only in the common case: the backend has just loaded the
|
|
306
|
+
* cwd ancestor chain itself, so recording those paths in the shared cache is what stops the
|
|
307
|
+
* first PostToolUse from injecting them a second time.
|
|
230
308
|
*/
|
|
231
309
|
export function runHook(payload, env = process.env) {
|
|
232
310
|
const paths = hookPaths(env);
|
|
@@ -236,6 +314,10 @@ export function runHook(payload, env = process.env) {
|
|
|
236
314
|
const sessionId = stableSessionId && SESSION_ID_RE.test(stableSessionId)
|
|
237
315
|
? stableSessionId
|
|
238
316
|
: payload.session_id;
|
|
317
|
+
// Default to PI, the backend with the SMALLER native coverage. Guessing "claude" for an
|
|
318
|
+
// undeclared spawn would make us skip descendants of cwd that PI never loads — a silent loss of
|
|
319
|
+
// rules. Guessing "pi" only risks injecting something Claude already had: wasteful, never wrong.
|
|
320
|
+
const backend = env.CORTEX_BACKEND?.trim() === 'claude' ? 'claude' : 'pi';
|
|
239
321
|
|
|
240
322
|
let scanRoot = null;
|
|
241
323
|
if (hookEventName === 'PostToolUse') {
|
|
@@ -250,13 +332,22 @@ export function runHook(payload, env = process.env) {
|
|
|
250
332
|
const entries = scanChain(scanRoot, paths);
|
|
251
333
|
if (entries.length === 0) return null;
|
|
252
334
|
|
|
335
|
+
const cwd = typeof payload.cwd === 'string' && payload.cwd ? resolve(payload.cwd) : null;
|
|
336
|
+
const claudeUsesAgentsMd = backend === 'claude' && cwd ? !claudeMdInChain(cwd) : false;
|
|
337
|
+
|
|
253
338
|
const lock = acquireLock(sessionId, paths);
|
|
254
339
|
try {
|
|
255
340
|
const cache = loadCache(sessionId, paths);
|
|
341
|
+
|
|
342
|
+
// Paths whose mtime we record without injecting: the file the tool just returned in full,
|
|
343
|
+
// plus everything the backend loaded on its own.
|
|
256
344
|
const markOnlyPaths = new Set();
|
|
257
345
|
if (hookEventName === 'PostToolUse') {
|
|
258
346
|
const targetPath = resolve(payload.tool_input?.file_path || payload.tool_input?.path || '');
|
|
259
|
-
if (
|
|
347
|
+
if (AGENTS_MD_NAMES.includes(basename(targetPath))) markOnlyPaths.add(targetPath);
|
|
348
|
+
}
|
|
349
|
+
for (const entry of entries) {
|
|
350
|
+
if (backendLoadsNatively(entry, cwd, backend, claudeUsesAgentsMd)) markOnlyPaths.add(entry.path);
|
|
260
351
|
}
|
|
261
352
|
|
|
262
353
|
let changed = false;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// input: node:http and Cortex hook environment
|
|
2
|
-
// output: askUser helper @cortex-hook-version 2026.
|
|
2
|
+
// output: askUser helper @cortex-hook-version 2026.9.15
|
|
3
3
|
// pos: Hook script interaction client
|
|
4
|
-
// >>> If updated, update this header and the folder
|
|
4
|
+
// >>> If updated, update this header and the folder AGENTS.md <<<
|
|
5
5
|
|
|
6
6
|
import http from 'node:http';
|
|
7
7
|
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// @cortex-hook-version 2026.
|
|
2
|
+
// @cortex-hook-version 2026.9.15-2
|
|
3
3
|
// input: stdin { channel, sessionId, sessionName, trigger, timestampIso } + env CORTEX_HOOK_*
|
|
4
4
|
// output: stdout — prompt to inject into the closing session (empty stdout = skip)
|
|
5
5
|
// pos: !new pre-close memory flush hook — recall valuable user and project info from the session, write to corresponding context files
|
|
6
|
-
// >>> If I am updated, be sure to update my header comment and the
|
|
6
|
+
// >>> If I am updated, be sure to update my header comment and the AGENTS.md in the same folder <<<
|
|
7
7
|
|
|
8
8
|
import { execSync } from 'child_process';
|
|
9
9
|
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// @cortex-hook-version 2026.
|
|
2
|
+
// @cortex-hook-version 2026.9.15-2
|
|
3
3
|
// input: stdin JSON — Claude Code PostToolUse event or PI hook-bridge payload
|
|
4
4
|
// output: { matched: [...], hookSpecificOutput: { additionalContext: "..." } }
|
|
5
5
|
// pos: Read/Grep hook — check if file path matches scoped rules in ~/.cortex/rules/
|
|
6
6
|
// On match, return rule content for Claude (additionalContext) and PI (content mutation) injection
|
|
7
7
|
// Session-level dedup: each rule injected at most once per session (on first match)
|
|
8
|
-
// >>> If I am updated, be sure to update my header comment and the
|
|
8
|
+
// >>> If I am updated, be sure to update my header comment and the AGENTS.md in the same folder <<<
|
|
9
9
|
|
|
10
10
|
import { readFileSync, readdirSync, statSync, existsSync, mkdirSync, renameSync, writeFileSync } from 'fs';
|
|
11
11
|
import { join, resolve, dirname } from 'path';
|