@compr/opscontext-mcp 2.7.0 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,22 @@ All notable changes to OpsContext for AI Agents (previously ContextEngine — MC
4
4
 
5
5
  > Entries for 2.2.0 through 2.4.0 were not backfilled here; see `docs/sessions/SESSION_19` through `SESSION_21` for those releases.
6
6
 
7
+ ## [2.7.1] 2026-09-06: the autostart agent is the standing indexer; servers --cost
8
+
9
+ ### Changed
10
+
11
+ - **`install-autostart` writes a plist that makes the agent the standing indexer**
12
+ (`[AUTOSTART-IS-THE-STANDING-INDEXER]`): `ProcessType Standard` instead of `Background` (as
13
+ Background it got 2.5 s of CPU in 15 minutes under load and served nobody),
14
+ `CONTEXTENGINE_SHARED_INDEX=1`, and `CONTEXTENGINE_CONFIG` / `CONTEXTENGINE_WORKSPACES` passed
15
+ through from the installing shell so its corpus id equals the chats'. The Claude-memory skip is
16
+ no longer a default; it is passed through only when the installer itself ran with it. Re-run
17
+ `install-autostart --force` to pick this up.
18
+ - **`contextengine servers --cost`**: CPU time and resident memory per server and in total, the
19
+ number that was invisible on 2026-09-05 until someone ran `ps` by hand.
20
+ - **The session-gate wrapper prefers a global install** of the CLI (`npm root -g`) over the
21
+ directory the installer ran from, so an npx cache prune cannot break the Stop hook.
22
+
7
23
  ## [2.7.0] 2026-09-06: the session gate ships in the package
8
24
 
9
25
  ### Added
package/README.md CHANGED
@@ -162,9 +162,11 @@ Companion commands: `uninstall-autostart`, `autostart-status`.
162
162
  **3c. Wire Claude Code terminal sessions**
163
163
 
164
164
  ```bash
165
- npx @compr/opscontext-mcp install-claude-hook
165
+ npm i -g @compr/opscontext-mcp && opscontext install-claude-hook
166
166
  ```
167
167
 
168
+ (Prefer the global install here: the hook scripts keep absolute paths to the CLI, and an `npx` cache copy can be pruned.)
169
+
168
170
  Adds `UserPromptSubmit`, `PostToolUse`, and `SessionStart` hook entries to `~/.claude/settings.json` so every Claude Code prompt + tool call lands in the same audit log as the browser events, plus a `Stop` entry: the **session gate** (2.7.0). A Claude Code turn cannot end while the repo's OpsContext session is older than the last commit; the agent is told which session to save, which session doc to update, and how far the agent docs are behind. No more "did you save the session?" at the end of a day. Details: `npx @compr/opscontext-mcp session-gate --help`.
169
171
 
170
172
  Verify:
package/dist/cli.js CHANGED
@@ -2527,7 +2527,7 @@ Usage:
2527
2527
  Export hash-chained audit log (evidence aligned with
2528
2528
  SOC 2 CC7.2 + ISO 27001 A.12.4.1 — not a certification)
2529
2529
  contextengine audit-verify Verify audit log chain integrity (tamper detection)
2530
- contextengine servers List running MCP servers, their build vs the file on disk
2530
+ contextengine servers [--cost] List running MCP servers, their build vs the file on disk, role; --cost adds CPU time and memory
2531
2531
  contextengine audit-redact-ack Acknowledge deliberately redacted records on the chain (--index i,j --reason "...")
2532
2532
  contextengine audit-rotate [--keep-days N] [--max-records N] [--dry-run]
2533
2533
  Move old history into an archive segment. Archives
@@ -2742,7 +2742,7 @@ else if (command === "audit-rotate") {
2742
2742
  }
2743
2743
  else if (command === "servers") {
2744
2744
  const fleet = listServers();
2745
- console.log(formatServers(fleet));
2745
+ console.log(formatServers(fleet, undefined, { cost: process.argv.includes("--cost") }));
2746
2746
  process.exit(fleet.warnings.length > 0 ? 1 : 0);
2747
2747
  }
2748
2748
  else if (command === "audit-verify") {
package/dist/index.js CHANGED
@@ -1402,6 +1402,14 @@ async function main() {
1402
1402
  else
1403
1403
  startIndexPolling();
1404
1404
  startRolePolling();
1405
+ // 5b. A daemon (launchd, OPSCONTEXT_DAEMON=1) has stdin on /dev/null, so the stdio transport
1406
+ // closes at once; as a reader it holds no watchers and every poller is unref'd, and the loop
1407
+ // would drain and exit 0, which KeepAlive turns into a restart every 10 s. Hold the loop open.
1408
+ // [LOCK] [AUTOSTART-IS-THE-STANDING-INDEXER]
1409
+ if (process.env.OPSCONTEXT_DAEMON === "1") {
1410
+ setInterval(() => { }, 60_000);
1411
+ console.error("[ContextEngine] 🛡 Daemon mode: staying alive without an MCP client");
1412
+ }
1405
1413
  // 6. Boot the local HTTP event-ingest endpoint for the browser extension.
1406
1414
  // Local 127.0.0.1:7842 only; auth via shared secret at
1407
1415
  // ~/.contextengine/extension-secret (see init-extension-secret CLI).
@@ -1,3 +1,4 @@
1
+ export declare function buildPlist(nodePath: string, entryPath: string, nodeBinDir: string, env?: NodeJS.ProcessEnv): string;
1
2
  export declare function cliInstallAutostart(args: string[]): Promise<void>;
2
3
  export declare function cliUninstallAutostart(args: string[]): Promise<void>;
3
4
  export declare function cliAutostartStatus(args: string[]): Promise<void>;
@@ -87,7 +87,30 @@ function detectOpscontextEntry() {
87
87
  }
88
88
  return null;
89
89
  }
90
- function buildPlist(nodePath, entryPath, nodeBinDir) {
90
+ // [LOCKED] [AUTOSTART-IS-THE-STANDING-INDEXER] 2026-09-06
91
+ // [NEVER] run the agent as ProcessType Background, drop CONTEXTENGINE_SHARED_INDEX from its
92
+ // environment, or give it a corpus the chats do not have.
93
+ // WHY: measured 2026-09-05 (SESSION_26): as Background the agent got 2.5 s of CPU in 15 minutes
94
+ // under load, took 4.5 min from exec to main(), served no MCP client (stdin is /dev/null),
95
+ // lost the browser-event port to whichever chat started first, and, with the memory skip and
96
+ // no config, indexed a corpus no chat used. It burned CPU keeping a cache warm that never
97
+ // hit. As the standing indexer it is the oldest server at every login, so it wins the
98
+ // election, every chat opens onto a ready index, and it owns the port from boot.
99
+ // FIX: Standard priority; the shared-index flag; CONTEXTENGINE_CONFIG passed through from the
100
+ // installing shell so its corpus id equals the chats'; the memory skip only if the installer
101
+ // was itself run with it (an explicit choice, not a default).
102
+ export function buildPlist(nodePath, entryPath, nodeBinDir, env = process.env) {
103
+ // OPSCONTEXT_DAEMON tells the server it has no MCP client on stdin and must stay alive on its
104
+ // own: as a reader it holds no file watchers, and every poller is unref'd, so without this the
105
+ // event loop drained and launchd restarted it every 10 s (found 2026-09-06, first real run).
106
+ const passthrough = [["CONTEXTENGINE_SHARED_INDEX", "1"], ["OPSCONTEXT_DAEMON", "1"]];
107
+ if (env.CONTEXTENGINE_CONFIG)
108
+ passthrough.push(["CONTEXTENGINE_CONFIG", env.CONTEXTENGINE_CONFIG]);
109
+ if (env.CONTEXTENGINE_WORKSPACES)
110
+ passthrough.push(["CONTEXTENGINE_WORKSPACES", env.CONTEXTENGINE_WORKSPACES]);
111
+ if (env.OPSCONTEXT_SKIP_CLAUDE_MEMORY === "1")
112
+ passthrough.push(["OPSCONTEXT_SKIP_CLAUDE_MEMORY", "1"]);
113
+ const extraEnv = passthrough.map(([k, v]) => ` <key>${k}</key>\n <string>${v.replace(/&/g, "&amp;").replace(/</g, "&lt;")}</string>`).join("\n");
91
114
  return `<?xml version="1.0" encoding="UTF-8"?>
92
115
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
93
116
  <plist version="1.0">
@@ -107,8 +130,7 @@ function buildPlist(nodePath, entryPath, nodeBinDir) {
107
130
  <string>${nodeBinDir}:/usr/local/bin:/usr/bin:/bin</string>
108
131
  <key>HOME</key>
109
132
  <string>${homedir()}</string>
110
- <key>OPSCONTEXT_SKIP_CLAUDE_MEMORY</key>
111
- <string>1</string>
133
+ ${extraEnv}
112
134
  </dict>
113
135
 
114
136
  <key>WorkingDirectory</key>
@@ -130,7 +152,7 @@ function buildPlist(nodePath, entryPath, nodeBinDir) {
130
152
  <string>${join(LOG_DIR, "mcp-stderr.log")}</string>
131
153
 
132
154
  <key>ProcessType</key>
133
- <string>Background</string>
155
+ <string>Standard</string>
134
156
  </dict>
135
157
  </plist>
136
158
  `;
@@ -18,6 +18,7 @@ import { existsSync, readFileSync, writeFileSync, copyFileSync, chmodSync, mkdir
18
18
  import { join, dirname } from "path";
19
19
  import { homedir } from "os";
20
20
  import { fileURLToPath } from "url";
21
+ import { execSync } from "child_process";
21
22
  // [LOCK] [M2-ESM-FILENAME-FIX]: the package is "type": "module", so a bare __dirname is a
22
23
  // ReferenceError at runtime. Found 2026-09-06 while adding the Stop gate: the defaults/ lookup
23
24
  // below used `__dirname_esm`, and a real run against a throwaway HOME died with
@@ -70,6 +71,17 @@ function bundledHookSource() {
70
71
  }
71
72
  return null;
72
73
  }
74
+ /** dist/cli.js of a global install, when there is one (same preference as install-autostart). */
75
+ function globalCliPath() {
76
+ try {
77
+ const root = execSync("npm root -g 2>/dev/null", { encoding: "utf-8" }).trim();
78
+ const c = join(root, "@compr", "opscontext-mcp", "dist", "cli.js");
79
+ return existsSync(c) ? c : null;
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ }
73
85
  export async function cliInstallClaudeHook(args) {
74
86
  const help = args.includes("-h") || args.includes("--help");
75
87
  if (help) {
@@ -143,7 +155,8 @@ Run: opscontext install-autostart
143
155
  added++;
144
156
  }
145
157
  // Step 3: the Stop gate. Absolute node + CLI paths: hooks run without the user's shell PATH.
146
- const cliPath = join(__dirname_esm, "cli.js");
158
+ // Prefer the global install: an npx cache copy can be pruned and the hook would then exit 127.
159
+ const cliPath = globalCliPath() ?? join(__dirname_esm, "cli.js");
147
160
  writeFileSync(GATE_SCRIPT, `#!/bin/sh\n# Generated by \`opscontext install-claude-hook\`: the CE session gate on Claude Code Stop.\n# Exit 2 = the turn may not end yet (reason on stderr). See: contextengine session-gate --help\nexec "${process.execPath}" "${cliPath}" session-gate\n`);
148
161
  chmodSync(GATE_SCRIPT, 0o755);
149
162
  settings.hooks.Stop ??= [];
@@ -43,5 +43,17 @@ export declare function registerServer(opts: {
43
43
  };
44
44
  /** Read every record, drop the dead ones, compare builds with the files on disk now. */
45
45
  export declare function listServers(): ServerReport;
46
- export declare function formatServers(report: ServerReport, home?: string): string;
46
+ /** CPU seconds consumed and resident memory of a live pid, from ps (hardcoded argv, no shell). */
47
+ export declare function processCost(pid: number): {
48
+ cpuSeconds: number;
49
+ rssMb: number;
50
+ } | null;
51
+ /**
52
+ * The listing. With `cost`, each line also carries CPU time and memory, and the total: this is
53
+ * the number that was invisible on 2026-09-05 (9.3 CPU-hours across eleven servers) until
54
+ * someone ran ps by hand. [LOCK] [ONE-INDEXER-MANY-READERS]
55
+ */
56
+ export declare function formatServers(report: ServerReport, home?: string, opts?: {
57
+ cost?: boolean;
58
+ }): string;
47
59
  //# sourceMappingURL=server-registry.d.ts.map
@@ -145,16 +145,57 @@ export function listServers() {
145
145
  }
146
146
  return report;
147
147
  }
148
- export function formatServers(report, home = homedir()) {
148
+ /** CPU seconds consumed and resident memory of a live pid, from ps (hardcoded argv, no shell). */
149
+ export function processCost(pid) {
150
+ try {
151
+ const out = execFileSync("ps", ["-o", "time=,rss=", "-p", String(pid)], { encoding: "utf8", timeout: 2000 }).trim();
152
+ const [time, rss] = out.split(/\s+/);
153
+ if (!time)
154
+ return null;
155
+ const parts = time.split(":").map(Number);
156
+ const cpuSeconds = parts.length === 3 ? parts[0] * 3600 + parts[1] * 60 + parts[2] : parts[0] * 60 + (parts[1] || 0);
157
+ return { cpuSeconds, rssMb: Math.round(Number(rss || 0) / 1024) };
158
+ }
159
+ catch {
160
+ return null;
161
+ }
162
+ }
163
+ function fmtCpu(s) {
164
+ if (s >= 3600)
165
+ return `${(s / 3600).toFixed(1)} CPU-h`;
166
+ if (s >= 60)
167
+ return `${Math.round(s / 60)} CPU-min`;
168
+ return `${Math.round(s)} CPU-s`;
169
+ }
170
+ /**
171
+ * The listing. With `cost`, each line also carries CPU time and memory, and the total: this is
172
+ * the number that was invisible on 2026-09-05 (9.3 CPU-hours across eleven servers) until
173
+ * someone ran ps by hand. [LOCK] [ONE-INDEXER-MANY-READERS]
174
+ */
175
+ export function formatServers(report, home = homedir(), opts = {}) {
149
176
  const short = (p) => p.startsWith(home) ? "~" + p.slice(home.length) : p;
150
177
  const lines = [];
151
178
  lines.push(`${report.servers.length} server(s) running${report.removed ? `, ${report.removed} dead record(s) removed` : ""}`);
179
+ let cpuTotal = 0, rssTotal = 0;
152
180
  for (const s of report.servers) {
153
181
  const t = s.started.slice(11, 19) + "Z";
154
182
  const flag = s.staleBuild ? `STALE BUILD (disk ${s.currentBuild})` : s.currentBuild === null ? "script missing on disk" : "current";
155
183
  const role = s.role ? ` ${s.role.padEnd(7)} corpus ${s.corpus ?? "?"}` : "";
156
- lines.push(` pid ${String(s.pid).padEnd(6)} ${t} v${s.version} build ${s.build} ${flag}${role} parent ${s.parent} cwd ${short(s.cwd)}`);
184
+ let cost = "";
185
+ if (opts.cost) {
186
+ const c = processCost(s.pid);
187
+ if (c) {
188
+ cpuTotal += c.cpuSeconds;
189
+ rssTotal += c.rssMb;
190
+ cost = ` ${fmtCpu(c.cpuSeconds).padStart(11)} ${String(c.rssMb).padStart(5)} MB`;
191
+ }
192
+ else
193
+ cost = " (cost unknown)";
194
+ }
195
+ lines.push(` pid ${String(s.pid).padEnd(6)} ${t} v${s.version} build ${s.build} ${flag}${role}${cost} parent ${s.parent} cwd ${short(s.cwd)}`);
157
196
  }
197
+ if (opts.cost && report.servers.length > 0)
198
+ lines.push(` total: ${fmtCpu(cpuTotal)}, ${rssTotal} MB resident, across ${report.servers.length} server(s)`);
158
199
  for (const w of report.warnings)
159
200
  lines.push(` ⚠ ${w}`);
160
201
  return lines.join("\n");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@compr/opscontext-mcp",
3
- "version": "2.7.0",
3
+ "version": "2.7.1",
4
4
  "description": "OpsContext for AI Agents — read-only fleet visibility (PM2/nginx/Docker/git/cron) + tamper-evident audit log + policy-as-code hooks. The ops + compliance layer Claude Code can't grow natively.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",