@rubytech/create-maxy-code 0.1.331 → 0.1.333

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.
Files changed (42) hide show
  1. package/dist/__tests__/watchdog-deferred-arming.test.js +62 -0
  2. package/dist/index.js +82 -11
  3. package/package.json +1 -1
  4. package/payload/platform/lib/mcp-spawn-tee/dist/index.d.ts +24 -24
  5. package/payload/platform/lib/mcp-spawn-tee/dist/index.js +109 -75
  6. package/payload/platform/lib/mcp-spawn-tee/dist/index.js.map +1 -1
  7. package/payload/platform/lib/mcp-spawn-tee/src/__tests__/spawn-tee.test.ts +56 -19
  8. package/payload/platform/lib/mcp-spawn-tee/src/index.ts +112 -77
  9. package/payload/platform/neo4j/schema.cypher +58 -4
  10. package/payload/platform/plugins/admin/lib/mcp-spawn-tee/index.js +109 -75
  11. package/payload/platform/plugins/aeo/lib/mcp-spawn-tee/index.js +109 -75
  12. package/payload/platform/plugins/browser/lib/mcp-spawn-tee/index.js +109 -75
  13. package/payload/platform/plugins/contacts/lib/mcp-spawn-tee/index.js +109 -75
  14. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/group-create.test.d.ts +2 -0
  15. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/group-create.test.d.ts.map +1 -0
  16. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/group-create.test.js +112 -0
  17. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/group-create.test.js.map +1 -0
  18. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/group-manage.test.d.ts +2 -0
  19. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/group-manage.test.d.ts.map +1 -0
  20. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/group-manage.test.js +102 -0
  21. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/group-manage.test.js.map +1 -0
  22. package/payload/platform/plugins/contacts/mcp/dist/tools/group-create.d.ts.map +1 -1
  23. package/payload/platform/plugins/contacts/mcp/dist/tools/group-create.js +7 -2
  24. package/payload/platform/plugins/contacts/mcp/dist/tools/group-create.js.map +1 -1
  25. package/payload/platform/plugins/contacts/mcp/dist/tools/group-manage.d.ts.map +1 -1
  26. package/payload/platform/plugins/contacts/mcp/dist/tools/group-manage.js +5 -4
  27. package/payload/platform/plugins/contacts/mcp/dist/tools/group-manage.js.map +1 -1
  28. package/payload/platform/plugins/email/lib/mcp-spawn-tee/index.js +109 -75
  29. package/payload/platform/plugins/memory/lib/mcp-spawn-tee/index.js +109 -75
  30. package/payload/platform/plugins/memory/references/schema-estate-agent.md +17 -5
  31. package/payload/platform/plugins/outlook/lib/mcp-spawn-tee/index.js +109 -75
  32. package/payload/platform/plugins/quickbooks/lib/mcp-spawn-tee/index.js +109 -75
  33. package/payload/platform/plugins/replicate/lib/mcp-spawn-tee/index.js +109 -75
  34. package/payload/platform/plugins/scheduling/lib/mcp-spawn-tee/index.js +109 -75
  35. package/payload/platform/plugins/telegram/lib/mcp-spawn-tee/index.js +109 -75
  36. package/payload/platform/plugins/url-get/lib/mcp-spawn-tee/index.js +109 -75
  37. package/payload/platform/plugins/whatsapp/lib/mcp-spawn-tee/index.js +109 -75
  38. package/payload/platform/plugins/work/lib/mcp-spawn-tee/index.js +109 -75
  39. package/payload/platform/plugins/workflows/lib/mcp-spawn-tee/index.js +109 -75
  40. package/payload/platform/scripts/seed-neo4j.sh +18 -0
  41. package/payload/premium-plugins/writer-craft/lib/mcp-spawn-tee/index.js +109 -75
  42. package/payload/server/server.js +291 -213
@@ -1,22 +1,20 @@
1
1
  import { afterEach, beforeAll, describe, expect, it } from 'vitest'
2
2
  import { execFileSync, spawn, spawnSync } from 'node:child_process'
3
- import {
4
- existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync,
5
- } from 'node:fs'
3
+ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
6
4
  import { tmpdir } from 'node:os'
7
5
  import { dirname, join, resolve } from 'node:path'
8
6
  import { fileURLToPath } from 'node:url'
9
7
 
10
8
  const here = dirname(fileURLToPath(import.meta.url))
11
9
  const libRoot = resolve(here, '..', '..') // platform/lib/mcp-spawn-tee
12
- const wrapper = join(libRoot, 'dist', 'index.js')
10
+ const shim = join(libRoot, 'dist', 'index.js')
13
11
  const tsc = resolve(libRoot, '..', '..', 'node_modules', '.bin', 'tsc')
14
12
 
15
- // Build the real artifact once; tests then exercise the shipped wrapper, not a
13
+ // Build the real artifact once; tests exercise the shipped shim, not a
16
14
  // re-implementation — that is what catches stdio-wiring regressions.
17
15
  beforeAll(() => {
18
16
  execFileSync(tsc, ['-p', 'tsconfig.json'], { cwd: libRoot, stdio: 'inherit' })
19
- expect(existsSync(wrapper)).toBe(true)
17
+ expect(existsSync(shim)).toBe(true)
20
18
  })
21
19
 
22
20
  let tmp = ''
@@ -24,13 +22,13 @@ afterEach(() => { if (tmp) { rmSync(tmp, { recursive: true, force: true }); tmp
24
22
 
25
23
  function makeStub(body: string): { stub: string; logDir: string } {
26
24
  tmp = mkdtempSync(join(tmpdir(), 'spawn-tee-'))
27
- const stub = join(tmp, 'stub-child.js')
25
+ const stub = join(tmp, 'stub-entry.js')
28
26
  writeFileSync(stub, body, 'utf8')
29
27
  return { stub, logDir: join(tmp, 'logs') }
30
28
  }
31
29
 
32
30
  function runSync(stub: string, env: Record<string, string>) {
33
- return spawnSync(process.execPath, [wrapper, stub], {
31
+ return spawnSync(process.execPath, [shim, stub], {
34
32
  env: { ...process.env, SESSION_ID: '', PLATFORM_PORT: '', ...env },
35
33
  encoding: 'utf8',
36
34
  })
@@ -40,21 +38,28 @@ function sessionLog(logDir: string, server: string, sessionId: string): string {
40
38
  return readFileSync(join(logDir, `mcp-${server}-${sessionId}.log`), 'utf8')
41
39
  }
42
40
 
43
- describe('mcp-spawn-tee wrapper', () => {
44
- it('captures child stderr to a per-session file and emits one op=exit on clean exit', () => {
45
- const { stub, logDir } = makeStub('process.stderr.write("hello-from-child\\n"); process.exit(0)')
41
+ describe('mcp-spawn-tee in-process shim', () => {
42
+ it('runs the entry in the shim process one node runtime, not two', () => {
43
+ const { stub, logDir } = makeStub('process.stdout.write(String(process.pid)); process.exit(0)')
44
+ const r = runSync(stub, { LOG_DIR: logDir, SESSION_ID: 'pid1', MCP_SPAWN_TEE_NAME: 'stub' })
45
+ // The entry's process.pid equals the spawned shim's pid: same process.
46
+ expect(r.stdout).toBe(String(r.pid))
47
+ })
48
+
49
+ it('tees entry stderr to a per-session file and emits one op=exit on clean exit', () => {
50
+ const { stub, logDir } = makeStub('process.stderr.write("hello-from-entry\\n"); process.exit(0)')
46
51
  runSync(stub, { LOG_DIR: logDir, SESSION_ID: 'abcd1234-session', MCP_SPAWN_TEE_NAME: 'stub' })
47
52
  const log = sessionLog(logDir, 'stub', 'abcd1234-session')
48
- expect(log).toContain('hello-from-child')
53
+ expect(log).toContain('hello-from-entry')
49
54
  const exits = log.split('\n').filter((l) => l.includes('op=exit'))
50
55
  expect(exits).toHaveLength(1)
51
56
  expect(exits[0]).toContain('code=0')
52
57
  expect(exits[0]).toMatch(/lifetimeMs=\d+/)
53
58
  expect(exits[0]).toContain('stderr-tail=')
54
- expect(exits[0]).toContain('hello-from-child')
59
+ expect(exits[0]).toContain('hello-from-entry')
55
60
  })
56
61
 
57
- it('emits op=spawn at start and op=boot on first child stderr', () => {
62
+ it('emits op=spawn at start and op=boot on first entry stderr', () => {
58
63
  const { stub, logDir } = makeStub('process.stderr.write("[stub] boot line\\n"); process.exit(0)')
59
64
  runSync(stub, { LOG_DIR: logDir, SESSION_ID: 'sess-0001', MCP_SPAWN_TEE_NAME: 'stub' })
60
65
  const log = sessionLog(logDir, 'stub', 'sess-0001')
@@ -72,9 +77,9 @@ describe('mcp-spawn-tee wrapper', () => {
72
77
  expect(exit).toContain('signal=—')
73
78
  })
74
79
 
75
- it('op=exit carries the signal name when the child is killed', async () => {
80
+ it('op=exit carries the signal name when terminated by a catchable signal', async () => {
76
81
  const { stub, logDir } = makeStub('process.stderr.write("alive\\n"); setInterval(() => {}, 1000)')
77
- const cp = spawn(process.execPath, [wrapper, stub], {
82
+ const cp = spawn(process.execPath, [shim, stub], {
78
83
  env: { ...process.env, SESSION_ID: 'sig1', PLATFORM_PORT: '', LOG_DIR: logDir, MCP_SPAWN_TEE_NAME: 'stub' },
79
84
  })
80
85
  await new Promise((res) => setTimeout(res, 500))
@@ -82,12 +87,44 @@ describe('mcp-spawn-tee wrapper', () => {
82
87
  const exitCode = await new Promise<number | null>((res) => cp.on('exit', (code) => res(code)))
83
88
  const exit = sessionLog(logDir, 'stub', 'sig1').split('\n').find((l) => l.includes('op=exit'))!
84
89
  expect(exit).toContain('signal=SIGTERM')
85
- // The wrapper propagates a signal kill as 128+signum (SIGTERM=15 → 143),
86
- // not a flat 128 — otherwise the signal identity is lost in the exit status.
90
+ // The shim propagates a catchable-signal kill as 128+signum (SIGTERM=15 → 143).
87
91
  expect(exitCode).toBe(143)
88
92
  })
89
93
 
90
- it('passes child stdout through untouched (MCP transport intact)', () => {
94
+ it('defers to an entry-owned signal handler: a graceful exit reads code=0 signal=—, not a signal death', async () => {
95
+ // The entry installs its own SIGINT handler that exits cleanly — as the real
96
+ // MCP entries do (closeDriver then process.exit(0)). The shim must NOT stamp
97
+ // signal=SIGINT on that clean exit; it defers and the entry's exit wins.
98
+ const { stub, logDir } = makeStub(
99
+ 'process.on("SIGINT", () => { process.stderr.write("graceful\\n"); process.exit(0) }); ' +
100
+ 'process.stderr.write("ready\\n"); setInterval(() => {}, 1000)',
101
+ )
102
+ const cp = spawn(process.execPath, [shim, stub], {
103
+ env: { ...process.env, SESSION_ID: 'sigint-own', PLATFORM_PORT: '', LOG_DIR: logDir, MCP_SPAWN_TEE_NAME: 'stub' },
104
+ })
105
+ await new Promise((res) => setTimeout(res, 500))
106
+ cp.kill('SIGINT')
107
+ const exitCode = await new Promise<number | null>((res) => cp.on('exit', (code) => res(code)))
108
+ const exit = sessionLog(logDir, 'stub', 'sigint-own').split('\n').find((l) => l.includes('op=exit'))!
109
+ expect(exit).toContain('code=0')
110
+ expect(exit).toContain('signal=—')
111
+ expect(exitCode).toBe(0)
112
+ })
113
+
114
+ it('leaves stderr on disk but writes no op=exit when SIGKILLed (accepted gap)', async () => {
115
+ const { stub, logDir } = makeStub('process.stderr.write("pre-kill stderr\\n"); setInterval(() => {}, 1000)')
116
+ const cp = spawn(process.execPath, [shim, stub], {
117
+ env: { ...process.env, SESSION_ID: 'kill1', PLATFORM_PORT: '', LOG_DIR: logDir, MCP_SPAWN_TEE_NAME: 'stub' },
118
+ })
119
+ await new Promise((res) => setTimeout(res, 500))
120
+ cp.kill('SIGKILL')
121
+ await new Promise<void>((res) => cp.on('exit', () => res()))
122
+ const log = sessionLog(logDir, 'stub', 'kill1')
123
+ expect(log).toContain('pre-kill stderr')
124
+ expect(log).not.toContain('op=exit')
125
+ })
126
+
127
+ it('passes entry stdout through untouched (MCP transport intact)', () => {
91
128
  const { stub, logDir } = makeStub('process.stdout.write("JSONRPC-PAYLOAD"); process.exit(0)')
92
129
  const r = runSync(stub, { LOG_DIR: logDir, SESSION_ID: 'out1', MCP_SPAWN_TEE_NAME: 'stub' })
93
130
  expect(r.stdout).toBe('JSONRPC-PAYLOAD')
@@ -1,46 +1,46 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * MCP spawn-tee — parent-side stderr capture + lifecycle observability.
3
+ * MCP spawn-tee — in-process stderr capture + lifecycle observability.
4
4
  *
5
5
  * Claude Code spawns each MCP server itself; the platform never holds a
6
- * ChildProcess handle. This wrapper sits between Claude Code and the real
7
- * MCP server: Claude Code runs `node <this> <real-entry>`, and the wrapper
8
- * spawns the real entry with `stdio:['inherit','inherit','pipe']` so stdin
9
- * and stdout (the JSON-RPC channel) pass through byte-identical. Only stderr
10
- * is intercepted, and only for logging.
6
+ * ChildProcess handle. This shim sits between Claude Code and the real MCP
7
+ * server: Claude Code runs `node <this> <real-entry>`, and the shim runs the
8
+ * real entry IN ITS OWN PROCESS via dynamic import() — one node runtime, not
9
+ * two. Before importing, it replaces process.stderr.write with a tee so every
10
+ * stderr byte the server writes is mirrored to the log sinks; stdin and stdout
11
+ * (the JSON-RPC channel) are never touched.
11
12
  *
12
- * Because the wrapper IS the helper's parent, it observes the helper's true
13
- * exit code, signal, and lifetime for every death mode — including a SIGKILL
14
- * or a transport-layer crash that an in-process handler would miss.
13
+ * Claude Code CLI shim (this file) = node running <real-entry> in-process
14
+ * stdin/stdout : untouched (JSON-RPC channel)
15
+ * stderr : process.stderr.write teed → per-date + per-session + passthrough
15
16
  *
16
- * Claude Code CLI → wrapper (this file) child = node <real-entry>
17
- * child stdin/stdout : inherited (Claude Code pipe, untouched)
18
- * child stderr : piped → per-date log + per-session log + passthrough
19
- *
20
- * Destinations (Task 706):
17
+ * Destinations (Task 706) unchanged:
21
18
  * - `${LOG_DIR}/mcp-<name>-stderr-<date>.log` — per-date raw (back-compat;
22
19
  * the in-process mcp-stderr-tee and the [mcp-init-error] probe read it).
23
20
  * - `${LOG_DIR}/mcp-<name>-<SESSION_ID>.log` — per-session raw + lifecycle
24
- * lines; wrapper-only, so it never mixes the enumeration copy with the
25
- * live copy. Authoritative sink. Absent when SESSION_ID is unset
26
- * (enumeration spawn) — then the per-date file is the fallback.
21
+ * lines. Authoritative sink. Absent when SESSION_ID is unset (enumeration
22
+ * spawn) then the per-date file is the fallback.
27
23
  * - `server.log` via the loopback log-ingest route — best-effort mirror of
28
- * the [mcp-helper] lifecycle lines. A dropped POST loses nothing because
29
- * the per-session file already holds the line (written synchronously).
24
+ * the [mcp-helper] lifecycle lines.
30
25
  *
31
- * Lifecycle lines, correlation key `session=<id8> server=<name>`:
26
+ * Lifecycle lines, correlation key `session=<id8> server=<name>` — unchanged:
32
27
  * [mcp-helper] op=spawn ... pid= entry=
33
28
  * [mcp-helper] op=boot ... head=<first stderr bytes>
34
- * [mcp-helper] op=exit ... code= signal= lifetimeMs= stderr-tail= (always)
29
+ * [mcp-helper] op=exit ... code= signal= lifetimeMs= stderr-tail=
30
+ *
31
+ * Process model (Task 989): the shim IS the server's process. op=exit fires
32
+ * from process.on("exit"), so it covers a normal exit, a non-zero exit, an
33
+ * uncaught throw (code 1), and a catchable-signal exit (SIGTERM/SIGINT/SIGHUP,
34
+ * whose handlers record the signal name). An external SIGKILL is uncatchable
35
+ * and leaves no op=exit line — the per-session stderr tail already on disk and
36
+ * Claude Code's own transport-drop are the evidence for that death mode.
35
37
  *
36
- * The wrapper never writes to fd 1 (stdout) — that is the JSON-RPC channel.
37
- * SIGTERM/SIGINT are forwarded to the child so a Claude Code shutdown does
38
- * not orphan it; the child exit code/signal is propagated verbatim.
38
+ * The shim never writes to fd 1 (stdout) — that is the JSON-RPC channel.
39
39
  */
40
40
 
41
- import { spawn } from "node:child_process";
42
41
  import { appendFileSync, mkdirSync } from "node:fs";
43
42
  import { resolve } from "node:path";
43
+ import { pathToFileURL } from "node:url";
44
44
 
45
45
  const SERVER_NAME = process.env.MCP_SPAWN_TEE_NAME ?? "unknown";
46
46
  const LOG_DIR = process.env.LOG_DIR;
@@ -51,8 +51,8 @@ const ENTRY = process.argv[2];
51
51
  const SESSION_ID8 = SESSION_ID ? SESSION_ID.slice(0, 8) : "—";
52
52
  const spawnStamp = Date.now();
53
53
 
54
- // Per-session raw + lifecycle log (Task 706). Wrapper-only. Empty SESSION_ID
55
- // (enumeration spawn) → undefined, and the per-date file is the fallback.
54
+ // Per-session raw + lifecycle log (Task 706). Empty SESSION_ID (enumeration
55
+ // spawn) → undefined, and the per-date file is the fallback.
56
56
  const perSessionPath = LOG_DIR && SESSION_ID
57
57
  ? resolve(LOG_DIR, `mcp-${SERVER_NAME}-${SESSION_ID}.log`)
58
58
  : undefined;
@@ -60,16 +60,28 @@ const perDatePath = LOG_DIR
60
60
  ? resolve(LOG_DIR, `mcp-${SERVER_NAME}-stderr-${new Date(spawnStamp).toISOString().slice(0, 10)}.log`)
61
61
  : undefined;
62
62
 
63
- // Rolling tail of child stderr for op=exit. Capped so a chatty child cannot
63
+ // Rolling tail of entry stderr for op=exit. Capped so a chatty server cannot
64
64
  // grow the buffer without bound.
65
65
  const TAIL_CAP = 2048;
66
66
  let stderrTail = "";
67
67
  let bootEmitted = false;
68
+ let exitEmitted = false;
69
+ let exitSignal: NodeJS.Signals | undefined;
70
+
71
+ // The real stderr writer, captured before the tee replaces it. Lifecycle lines
72
+ // and stderr passthrough both go through this so they are never re-teed into
73
+ // the per-date sink nor recursed back into the patched writer.
74
+ const rawStderrWrite = process.stderr.write.bind(process.stderr);
75
+
76
+ // LOG_DIR is created once, lazily, on the first successful append — not per
77
+ // chunk. teeWrite runs on the server's own stderr hot path now, so a per-call
78
+ // mkdirSync would be two syscalls per log line for nothing.
79
+ let logDirReady = false;
68
80
 
69
81
  function appendSafe(path: string | undefined, data: string | Uint8Array): void {
70
82
  if (!path || !LOG_DIR) return;
71
83
  try {
72
- mkdirSync(LOG_DIR, { recursive: true });
84
+ if (!logDirReady) { mkdirSync(LOG_DIR, { recursive: true }); logDirReady = true; }
73
85
  appendFileSync(path, data);
74
86
  } catch {
75
87
  /* unwritable destination — never mask primary output */
@@ -77,14 +89,15 @@ function appendSafe(path: string | undefined, data: string | Uint8Array): void {
77
89
  }
78
90
 
79
91
  // Best-effort mirror of a lifecycle line to server.log via the loopback
80
- // log-ingest route. Fire-and-forget: the per-session file is authoritative,
81
- // so a dropped POST (unreachable port, process exiting) loses nothing.
92
+ // log-ingest route. Fire-and-forget: the per-session file is authoritative, so
93
+ // a dropped POST loses nothing. On the "exit" event the loop is stopping, so
94
+ // the op=exit mirror may not flush — the per-session line, written sync, holds.
82
95
  function postToServerLog(suffix: string, level: "info" | "error"): void {
83
96
  if (!PLATFORM_PORT) return;
84
97
  try {
85
98
  const ctrl = new AbortController();
86
99
  const t = setTimeout(() => ctrl.abort(), 500);
87
- t.unref?.(); // never let the abort timer keep the wrapper's event loop alive
100
+ t.unref?.(); // never let the abort timer keep the shim's event loop alive
88
101
  void fetch(`http://127.0.0.1:${PLATFORM_PORT}/api/admin/log-ingest`, {
89
102
  method: "POST",
90
103
  headers: { "content-type": "application/json" },
@@ -97,13 +110,14 @@ function postToServerLog(suffix: string, level: "info" | "error"): void {
97
110
  }
98
111
 
99
112
  // Emit one [mcp-helper] lifecycle line: authoritative per-session file (sync,
100
- // survives process.exit), the wrapper's own stderr (journald / Claude Code
101
- // visibility), and a best-effort server.log mirror. `suffix` is the line body
102
- // after the tag and carries no newline (the log-ingest route rejects newlines).
113
+ // survives process.exit), the shim's own stderr via the RAW writer (journald /
114
+ // Claude Code visibility, never re-teed), and a best-effort server.log mirror.
115
+ // `suffix` is the line body after the tag and carries no newline (the
116
+ // log-ingest route rejects newlines).
103
117
  function emitLifecycle(suffix: string, level: "info" | "error"): void {
104
118
  const line = `[mcp-helper] ${suffix}\n`;
105
119
  appendSafe(perSessionPath, line);
106
- try { process.stderr.write(line); } catch { /* stderr closed */ }
120
+ try { rawStderrWrite(line); } catch { /* stderr closed */ }
107
121
  postToServerLog(suffix, level);
108
122
  }
109
123
 
@@ -112,52 +126,73 @@ if (!ENTRY) {
112
126
  process.exit(2);
113
127
  }
114
128
 
115
- const child = spawn(process.execPath, [ENTRY], {
116
- stdio: ["inherit", "inherit", "pipe"],
117
- env: process.env,
118
- });
119
-
120
- emitLifecycle(`op=spawn session=${SESSION_ID8} server=${SERVER_NAME} pid=${child.pid ?? -1} entry=${ENTRY}`, "info");
121
-
122
- child.on("error", (err) => {
123
- const msg = err instanceof Error ? err.message : String(err);
124
- emitLifecycle(`op=error session=${SESSION_ID8} server=${SERVER_NAME} reason=${JSON.stringify(`spawn error: ${msg}`)}`, "error");
125
- process.exit(127);
126
- });
127
-
128
- if (child.stderr) {
129
- child.stderr.on("data", (chunk: Buffer) => {
130
- appendSafe(perDatePath, chunk); // per-date raw (back-compat)
131
- appendSafe(perSessionPath, chunk); // per-session raw (Task 706)
132
- try { process.stderr.write(chunk); } catch { /* stderr closed */ } // passthrough
133
- stderrTail = (stderrTail + chunk.toString("utf8")).slice(-TAIL_CAP);
134
- if (!bootEmitted) {
135
- bootEmitted = true;
136
- const head = chunk.toString("utf8").split("\n")[0].slice(0, 200);
137
- emitLifecycle(`op=boot session=${SESSION_ID8} server=${SERVER_NAME} head=${JSON.stringify(head)}`, "info");
129
+ // Replace process.stderr.write with a tee: mirror every server stderr byte to
130
+ // the per-date and per-session sinks, keep a rolling tail for op=exit, emit
131
+ // op=boot on the first bytes, then pass the write through to the real stderr.
132
+ const teeWrite = ((...args: unknown[]): boolean => {
133
+ const chunk = args[0] as string | Uint8Array;
134
+ appendSafe(perDatePath, chunk); // per-date raw (back-compat)
135
+ appendSafe(perSessionPath, chunk); // per-session raw (Task 706)
136
+ const text = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
137
+ stderrTail = (stderrTail + text).slice(-TAIL_CAP);
138
+ if (!bootEmitted) {
139
+ bootEmitted = true;
140
+ const head = text.split("\n")[0].slice(0, 200);
141
+ emitLifecycle(`op=boot session=${SESSION_ID8} server=${SERVER_NAME} head=${JSON.stringify(head)}`, "info");
142
+ }
143
+ return (rawStderrWrite as (...a: unknown[]) => boolean)(...args); // passthrough
144
+ }) as typeof process.stderr.write;
145
+ process.stderr.write = teeWrite;
146
+
147
+ // Catchable-signal handling. The shim drives the exit ONLY when it is the sole
148
+ // listener for the signal — i.e. the imported entry installed no handler of its
149
+ // own. In that case it records the signal (so op=exit carries signal=<sig>) and
150
+ // exits with 128+signum, mirroring the prior wrapper's exit-status convention.
151
+ //
152
+ // When the entry DID install a handler, the shim defers entirely and records
153
+ // nothing: the entry's handler decides the exit code, and op=exit reflects that
154
+ // exit verbatim. This matches the prior two-process model, where a child that
155
+ // caught the signal and exited cleanly was observed as code=0 signal=— (a clean
156
+ // self-exit), not as a signal death. Setting exitSignal here unconditionally
157
+ // would mislabel every graceful signal-driven shutdown as a signal kill.
158
+ function onSignal(sig: NodeJS.Signals, code: number): () => void {
159
+ return () => {
160
+ if (process.listenerCount(sig) === 1) {
161
+ exitSignal = sig;
162
+ process.exit(code);
138
163
  }
139
- });
164
+ };
140
165
  }
141
-
142
- const forward = (signal: NodeJS.Signals) => { if (!child.killed) child.kill(signal); };
143
- process.on("SIGTERM", () => forward("SIGTERM"));
144
- process.on("SIGINT", () => forward("SIGINT"));
145
-
146
- // Signal number, so a signal-killed child propagates as 128+signum (the
147
- // shell convention). `code` is null on a signal exit, so `128 + (code ?? 0)`
148
- // would collapse every signal to 128 and lose the signal identity in the
149
- // wrapper's own exit status.
150
- const SIGNUM: Record<string, number> = { SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGKILL: 9, SIGTERM: 15 };
151
-
152
- child.on("exit", (code, signal) => {
166
+ process.on("SIGTERM", onSignal("SIGTERM", 143));
167
+ process.on("SIGINT", onSignal("SIGINT", 130));
168
+ process.on("SIGHUP", onSignal("SIGHUP", 129));
169
+
170
+ // op=exit, emitted once from the process "exit" event. Sync-only — the loop is
171
+ // stopping. When a catchable signal caused the exit, report code=— signal=<sig>
172
+ // to match the prior wrapper's format; otherwise code=<exit code> signal=—.
173
+ process.on("exit", (code) => {
174
+ if (exitEmitted) return;
175
+ exitEmitted = true;
153
176
  const lifetimeMs = Date.now() - spawnStamp;
154
177
  const tail = stderrTail.slice(-200);
155
- const level: "info" | "error" = signal || (code ?? 0) !== 0 ? "error" : "info";
178
+ const codeField = exitSignal ? "" : String(code);
179
+ const level: "info" | "error" = exitSignal || code !== 0 ? "error" : "info";
156
180
  emitLifecycle(
157
- `op=exit session=${SESSION_ID8} server=${SERVER_NAME} pid=${child.pid ?? -1} ` +
158
- `code=${code ?? "—"} signal=${signal ?? "—"} lifetimeMs=${lifetimeMs} stderr-tail=${JSON.stringify(tail)}`,
181
+ `op=exit session=${SESSION_ID8} server=${SERVER_NAME} pid=${process.pid} ` +
182
+ `code=${codeField} signal=${exitSignal ?? "—"} lifetimeMs=${lifetimeMs} stderr-tail=${JSON.stringify(tail)}`,
159
183
  level,
160
184
  );
161
- if (signal) process.exit(128 + (SIGNUM[signal] ?? 0));
162
- process.exit(code ?? 0);
185
+ });
186
+
187
+ emitLifecycle(`op=spawn session=${SESSION_ID8} server=${SERVER_NAME} pid=${process.pid} entry=${ENTRY}`, "info");
188
+
189
+ // Run the real MCP server in THIS process. Dynamic import() (not top-level
190
+ // await — this file compiles to CommonJS) loads the ESM entry; a load-time
191
+ // failure mirrors the old child spawn-error path (op=error, exit 127). The
192
+ // op=exit handler is suppressed on this path so op=error stays the sole record.
193
+ import(pathToFileURL(ENTRY).href).catch((err: unknown) => {
194
+ const msg = err instanceof Error ? err.message : String(err);
195
+ exitEmitted = true;
196
+ emitLifecycle(`op=error session=${SESSION_ID8} server=${SERVER_NAME} reason=${JSON.stringify(`import error: ${msg}`)}`, "error");
197
+ process.exit(127);
163
198
  });
@@ -1217,18 +1217,26 @@ CREATE INDEX cloudflare_hostname_account IF NOT EXISTS
1217
1217
  FOR (h:CloudflareHostname) ON (h.accountId);
1218
1218
 
1219
1219
  // ----------------------------------------------------------
1220
- // Estate-agent ontology (Task 358) — Listing-centric model
1220
+ // Estate-agent ontology (Task 358) — Property-centric model
1221
1221
  // documented at platform/plugins/memory/references/schema-estate-agent.md.
1222
1222
  //
1223
+ // :Property is the obligatory top-level node: the physical property, with
1224
+ // its listing events beneath it. It carries the agency parent edge
1225
+ // (:Property)-[:LISTED_BY]->(:Organization {brandSlug}) (the ≥1-adjacency
1226
+ // write-gate parent) and (:Property)-[:HAS_LISTING]->(:Listing) to each of
1227
+ // its listing events. The pre-inversion (:Listing)-[:FOR_PROPERTY]->(:Property)
1228
+ // and (:Listing)-[:LISTED_BY]->(:Organization) edges are retired.
1229
+ //
1223
1230
  // These declarations exist primarily so the memory-write validator's
1224
1231
  // parseLabelsFromSchemaCypher() registers each label on a fresh deploy
1225
1232
  // where no node of the label has yet landed — without them, the first
1226
- // :Listing write from the listing-curator agent is rejected as "unknown
1227
- // label" against an empty db.labels() set.
1233
+ // :Property/:Listing write from the listing-curator agent is rejected as
1234
+ // "unknown label" against an empty db.labels() set.
1228
1235
  //
1229
1236
  // Idempotency contracts mirror schema-estate-agent.md:
1237
+ // :Property — (accountId, slug) on the address-normalised
1238
+ // slug; the obligatory hub.
1230
1239
  // :Listing / :Viewing / :Offer — (accountId, sourceSystem, sourceId)
1231
- // :Property — (accountId, slug)
1232
1240
  // :ImageObject — (accountId, listingSlug, url) for the
1233
1241
  // estate-agent variant, (accountId, name,
1234
1242
  // contentUrl) for the brand-asset variant.
@@ -1237,6 +1245,12 @@ FOR (h:CloudflareHostname) ON (h.accountId);
1237
1245
  // declared at the schema level — uniqueness
1238
1246
  // is enforced at write time by the curator
1239
1247
  // / brand-asset writer's MERGE clause.
1248
+ //
1249
+ // :Property already carries the account index, the (accountId, slug) unique
1250
+ // constraint, and a slot in the entity_search_admin fulltext union (its
1251
+ // n.address is in the ON EACH list) — no new index is added for the hub
1252
+ // inversion. The marketing embedding stays on :Listing; semantic search
1253
+ // targets the listing blurb/description, not the structural hub.
1240
1254
  // ----------------------------------------------------------
1241
1255
 
1242
1256
  CREATE CONSTRAINT listing_account_source_unique IF NOT EXISTS
@@ -1266,6 +1280,46 @@ FOR (p:Property) REQUIRE (p.accountId, p.slug) IS UNIQUE;
1266
1280
  CREATE INDEX property_account IF NOT EXISTS
1267
1281
  FOR (p:Property) ON (p.accountId);
1268
1282
 
1283
+ // Property-hub backfill — relink listing-only estate data deployed before
1284
+ // :Property became obligatory. Three idempotent passes, mirroring the
1285
+ // conversationId one-shot migration pattern above. Installs with no :Listing
1286
+ // nodes (every non-estate brand) match nothing in any pass. The standing
1287
+ // reconcile that proves orphanListings reached 0 is emitted per-deploy by
1288
+ // platform/scripts/seed-neo4j.sh.
1289
+ //
1290
+ // Pass 1 — convert any pre-inversion (:Listing)-[:FOR_PROPERTY]->(:Property)
1291
+ // to the parent-down (:Property)-[:HAS_LISTING]->(:Listing), reusing the
1292
+ // existing :Property, then drop the retired edge. Idempotent: once
1293
+ // FOR_PROPERTY is deleted a re-run matches nothing.
1294
+ MATCH (l:Listing)-[fp:FOR_PROPERTY]->(p:Property)
1295
+ MERGE (p)-[:HAS_LISTING]->(l)
1296
+ DELETE fp;
1297
+
1298
+ // Pass 2 — for every :Listing still lacking a :Property parent, synthesise a
1299
+ // :Property from the listing's address slug and attach
1300
+ // (:Property)-[:HAS_LISTING]->(:Listing). Idempotent: the HAS_LISTING guard
1301
+ // makes re-runs and already-migrated listings no-ops. Listings with a null
1302
+ // slug are deliberately excluded — there is no address key to MERGE on, and a
1303
+ // {slug: null} MERGE would collapse every slug-less listing into one bogus
1304
+ // (accountId, null) :Property. Such listings (a malformed pre-inversion write)
1305
+ // stay visible as orphanListings in the seed-neo4j.sh reconcile; recovering
1306
+ // them needs an address backfill, tracked in .tasks/996-estate-null-slug-listing-property-backfill.md.
1307
+ MATCH (l:Listing)
1308
+ WHERE l.slug IS NOT NULL AND NOT ( (:Property)-[:HAS_LISTING]->(l) )
1309
+ MERGE (p:Property {accountId: l.accountId, slug: l.slug})
1310
+ ON CREATE SET p.address = coalesce(l.displayName, l.addressLine),
1311
+ p.postcode = l.postcode
1312
+ MERGE (p)-[:HAS_LISTING]->(l);
1313
+
1314
+ // Pass 3 — relocate the agency edge from each :Listing onto its :Property
1315
+ // parent. Bound per LISTED_BY edge (one row per edge), so the DELETE never
1316
+ // double-fires on a single relationship regardless of how many listings share
1317
+ // a :Property or how many edges a listing carries. Idempotent: once a
1318
+ // listing's LISTED_BY is moved, a re-run matches nothing.
1319
+ MATCH (p:Property)-[:HAS_LISTING]->(l:Listing)-[old:LISTED_BY]->(o:Organization)
1320
+ MERGE (p)-[:LISTED_BY]->(o)
1321
+ DELETE old;
1322
+
1269
1323
  CREATE CONSTRAINT viewing_account_source_unique IF NOT EXISTS
1270
1324
  FOR (v:Viewing) REQUIRE (v.accountId, v.sourceSystem, v.sourceId) IS UNIQUE;
1271
1325