@rubytech/create-sitedesk-code 0.1.437 → 0.1.439

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 (64) hide show
  1. package/package.json +1 -1
  2. package/payload/platform/lib/admin-access-password/__tests__/index.test.ts +31 -0
  3. package/payload/platform/lib/admin-access-password/dist/index.d.ts +8 -0
  4. package/payload/platform/lib/admin-access-password/dist/index.d.ts.map +1 -1
  5. package/payload/platform/lib/admin-access-password/dist/index.js +5 -1
  6. package/payload/platform/lib/admin-access-password/dist/index.js.map +1 -1
  7. package/payload/platform/lib/admin-access-password/src/index.ts +14 -1
  8. package/payload/platform/lib/admins-write/__tests__/index.test.ts +27 -0
  9. package/payload/platform/lib/admins-write/dist/index.d.ts +8 -0
  10. package/payload/platform/lib/admins-write/dist/index.d.ts.map +1 -1
  11. package/payload/platform/lib/admins-write/dist/index.js +5 -1
  12. package/payload/platform/lib/admins-write/dist/index.js.map +1 -1
  13. package/payload/platform/lib/admins-write/src/index.ts +14 -1
  14. package/payload/platform/plugins/admin/.claude-plugin/plugin.json +1 -1
  15. package/payload/platform/plugins/admin/PLUGIN.md +4 -2
  16. package/payload/platform/plugins/admin/mcp/dist/credential-identity.d.ts +23 -0
  17. package/payload/platform/plugins/admin/mcp/dist/credential-identity.d.ts.map +1 -0
  18. package/payload/platform/plugins/admin/mcp/dist/credential-identity.js +35 -0
  19. package/payload/platform/plugins/admin/mcp/dist/credential-identity.js.map +1 -0
  20. package/payload/platform/plugins/admin/mcp/dist/index.js +110 -57
  21. package/payload/platform/plugins/admin/mcp/dist/index.js.map +1 -1
  22. package/payload/platform/plugins/admin/mcp/dist/tools/account-lifecycle.d.ts +22 -0
  23. package/payload/platform/plugins/admin/mcp/dist/tools/account-lifecycle.d.ts.map +1 -1
  24. package/payload/platform/plugins/admin/mcp/dist/tools/account-lifecycle.js +62 -2
  25. package/payload/platform/plugins/admin/mcp/dist/tools/account-lifecycle.js.map +1 -1
  26. package/payload/platform/plugins/admin/skills/platform-architecture/SKILL.md +7 -1
  27. package/payload/platform/plugins/docs/references/admin-identity-gate.md +40 -0
  28. package/payload/platform/plugins/docs/references/internals.md +4 -0
  29. package/payload/platform/plugins/docs/references/plugins-guide.md +2 -0
  30. package/payload/platform/plugins/graph-viewer/.claude-plugin/plugin.json +13 -0
  31. package/payload/platform/plugins/graph-viewer/PLUGIN.md +1 -1
  32. package/payload/platform/plugins/graph-viewer/lib/mcp-spawn-tee/index.js +193 -0
  33. package/payload/platform/plugins/graph-viewer/lib/mcp-spawn-tee/package.json +3 -0
  34. package/payload/platform/plugins/linkedin-import/skills/linkedin-import/references/profile.md +1 -1
  35. package/payload/platform/scripts/remediate-glsmith-identity.sh +500 -0
  36. package/payload/platform/scripts/seed-neo4j.sh +77 -12
  37. package/payload/platform/services/claude-session-manager/dist/http-server.d.ts.map +1 -1
  38. package/payload/platform/services/claude-session-manager/dist/http-server.js +20 -4
  39. package/payload/platform/services/claude-session-manager/dist/http-server.js.map +1 -1
  40. package/payload/platform/services/claude-session-manager/dist/identity-audit.d.ts +51 -0
  41. package/payload/platform/services/claude-session-manager/dist/identity-audit.d.ts.map +1 -0
  42. package/payload/platform/services/claude-session-manager/dist/identity-audit.js +103 -0
  43. package/payload/platform/services/claude-session-manager/dist/identity-audit.js.map +1 -0
  44. package/payload/platform/services/claude-session-manager/dist/index.js +69 -0
  45. package/payload/platform/services/claude-session-manager/dist/index.js.map +1 -1
  46. package/payload/platform/services/claude-session-manager/dist/mcp-user-binding.d.ts +25 -0
  47. package/payload/platform/services/claude-session-manager/dist/mcp-user-binding.d.ts.map +1 -0
  48. package/payload/platform/services/claude-session-manager/dist/mcp-user-binding.js +42 -0
  49. package/payload/platform/services/claude-session-manager/dist/mcp-user-binding.js.map +1 -0
  50. package/payload/platform/services/claude-session-manager/dist/redundant-operator-seat-audit.d.ts +44 -0
  51. package/payload/platform/services/claude-session-manager/dist/redundant-operator-seat-audit.d.ts.map +1 -0
  52. package/payload/platform/services/claude-session-manager/dist/redundant-operator-seat-audit.js +127 -0
  53. package/payload/platform/services/claude-session-manager/dist/redundant-operator-seat-audit.js.map +1 -0
  54. package/payload/platform/services/claude-session-manager/dist/tool-registration-drift.d.ts +57 -0
  55. package/payload/platform/services/claude-session-manager/dist/tool-registration-drift.d.ts.map +1 -0
  56. package/payload/platform/services/claude-session-manager/dist/tool-registration-drift.js +147 -0
  57. package/payload/platform/services/claude-session-manager/dist/tool-registration-drift.js.map +1 -0
  58. package/payload/premium-plugins/sitedesk/plugins/sitedesk-job/.claude-plugin/plugin.json +13 -0
  59. package/payload/premium-plugins/sitedesk/plugins/sitedesk-job/PLUGIN.md +1 -1
  60. package/payload/premium-plugins/sitedesk/plugins/sitedesk-job/lib/mcp-spawn-tee/index.js +193 -0
  61. package/payload/premium-plugins/sitedesk/plugins/sitedesk-job/lib/mcp-spawn-tee/package.json +3 -0
  62. package/payload/server/{chunk-LMLVOZ6G.js → chunk-UGPQCVIW.js} +11 -38
  63. package/payload/server/maxy-edge.js +1 -1
  64. package/payload/server/server.js +15 -16
@@ -0,0 +1,127 @@
1
+ // Task 1568 — standing redundant-operator-seat audit. A role:"client" sub-account
2
+ // carries exactly one identity node, its business owner (AdminUser{role:'owner'}).
3
+ // Any other AdminUser{accountId} on a client account is a redundant operator seat:
4
+ // since Task 999 admin access is install-wide, so the seat grants nothing an
5
+ // install-wide admin does not already have, and it fragments identity. admin-add
6
+ // no longer creates one going forward; this periodic read is the only signal for
7
+ // seats persisted before that fix, because a redundant seat emits no error and
8
+ // does not reproduce on demand. Detector only — removal is a deliberate
9
+ // remediation (Task 1569), never an automatic timer-driven delete.
10
+ //
11
+ // admin-add seats carry no au.role (role 'admin' lives on the ADMIN_OF edge), so
12
+ // the predicate is not-the-owner rather than a role:'admin' match. Best-effort by
13
+ // construction: a Neo4j-unreachable read logs `op=unavailable` rather than
14
+ // crashing the manager (Neo4j may not be up at boot). Shape mirrors
15
+ // rootless-client-audit.ts: a pure predicate + formatter (unit-tested) + an
16
+ // impure collector + a start/stop factory whose setInterval is unref'd.
17
+ import neo4j from 'neo4j-driver';
18
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
19
+ import { join } from 'node:path';
20
+ const TAG = '[identity-audit]';
21
+ /** The redundant-seat invariant, read side: an AdminUser on a client account is a
22
+ * redundant operator seat unless it is the owner. admin-add seats carry no
23
+ * au.role, so the predicate is not-the-owner, never a role:'admin' match. */
24
+ export function isRedundantOperatorSeat(role) {
25
+ return (role ?? '').trim() !== 'owner';
26
+ }
27
+ /** One alarm line per flagged seat; ids truncated to 8 for readability. */
28
+ export function formatRedundantSeatLine(f) {
29
+ return `${TAG} op=redundant-operator-seat account=${f.accountId.slice(0, 8)} adminUserId=${f.adminUserId.slice(0, 8)}`;
30
+ }
31
+ /** Return every non-owner AdminUser seated on the given client accounts. One
32
+ * round-trip: the cypher returns all AdminUser{accountId} rows for the client
33
+ * ids and the not-owner filter is applied in JS (same predicate the audit
34
+ * exposes). Empty input issues no query. */
35
+ export async function auditRedundantOperatorSeats(session, clientIds) {
36
+ if (clientIds.length === 0)
37
+ return [];
38
+ const res = await session.run(`UNWIND $ids AS id
39
+ MATCH (au:AdminUser {accountId: id})
40
+ RETURN id AS accountId, coalesce(au.userId, '') AS adminUserId, au.role AS role`, { ids: clientIds });
41
+ const findings = [];
42
+ for (const rec of res.records) {
43
+ if (isRedundantOperatorSeat(rec.get('role'))) {
44
+ findings.push({
45
+ accountId: String(rec.get('accountId')),
46
+ adminUserId: String(rec.get('adminUserId')),
47
+ });
48
+ }
49
+ }
50
+ return findings;
51
+ }
52
+ /** Enumerate role:"client" accountIds under the accounts root (filesystem). */
53
+ function clientAccountIds(accountsRoot) {
54
+ let entries;
55
+ try {
56
+ entries = readdirSync(accountsRoot);
57
+ }
58
+ catch {
59
+ return [];
60
+ }
61
+ const out = [];
62
+ for (const entry of entries) {
63
+ const cfgPath = join(accountsRoot, entry, 'account.json');
64
+ if (!existsSync(cfgPath))
65
+ continue;
66
+ try {
67
+ const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));
68
+ if (cfg.role === 'client')
69
+ out.push(entry);
70
+ }
71
+ catch {
72
+ // unparseable account.json — excluded
73
+ }
74
+ }
75
+ return out;
76
+ }
77
+ /** Run one audit pass and log an alarm line per flagged seat. Best-effort Neo4j:
78
+ * absent env or an unreachable/erroring read logs `op=unavailable` and never
79
+ * throws. A clean pass logs a single `op=ok` line so the audit's own liveness is
80
+ * visible. */
81
+ export async function emitRedundantOperatorSeatAudit(deps) {
82
+ if (!deps.neo4jUri || !deps.neo4jPassword) {
83
+ deps.logger(`${TAG} op=unavailable reason=no-neo4j-env`);
84
+ return;
85
+ }
86
+ const driver = neo4j.driver(deps.neo4jUri, neo4j.auth.basic(deps.neo4jUser, deps.neo4jPassword));
87
+ const session = driver.session();
88
+ try {
89
+ const findings = await auditRedundantOperatorSeats(session, clientAccountIds(deps.accountsRoot));
90
+ if (findings.length === 0) {
91
+ deps.logger(`${TAG} op=ok redundant-operator-seats=0`);
92
+ return;
93
+ }
94
+ for (const f of findings)
95
+ deps.logger(formatRedundantSeatLine(f));
96
+ }
97
+ catch (err) {
98
+ deps.logger(`${TAG} op=unavailable reason=${err instanceof Error ? err.message : String(err)}`);
99
+ }
100
+ finally {
101
+ await session.close();
102
+ await driver.close();
103
+ }
104
+ }
105
+ /** Standing periodic audit. Unref'd interval so it never holds the process open;
106
+ * each tick re-emits best-effort. */
107
+ export function createRedundantOperatorSeatAudit(deps) {
108
+ let timer = null;
109
+ return {
110
+ start() {
111
+ if (timer)
112
+ return;
113
+ timer = setInterval(() => {
114
+ void emitRedundantOperatorSeatAudit(deps);
115
+ }, deps.intervalMs);
116
+ if (typeof timer.unref === 'function')
117
+ timer.unref();
118
+ },
119
+ stop() {
120
+ if (timer) {
121
+ clearInterval(timer);
122
+ timer = null;
123
+ }
124
+ },
125
+ };
126
+ }
127
+ //# sourceMappingURL=redundant-operator-seat-audit.js.map
@@ -0,0 +1 @@
1
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AK,8BAA8B,CAAC,IAAI,CAAC,CAAA;YAC3C,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,CAAA;YACnB,IAAI,OAAO,KAAK,CAAC,KAAK,KAAK,UAAU;gBAAE,KAAK,CAAC,KAAK,EAAE,CAAA;QACtD,CAAC;QACD,IAAI;YACF,IAAI,KAAK,EAAE,CAAC;gBACV,aAAa,CAAC,KAAK,CAAC,CAAA;gBACpB,KAAK,GAAG,IAAI,CAAA;YACd,CAAC;QACH,CAAC;KACF,CAAA;AACH,CAAC"}
@@ -0,0 +1,57 @@
1
+ export type ToolRegistrationDriftReason = 'not-installed' | 'no-mcpServers-manifest' | 'dist-missing';
2
+ /** The generated-manifest disposition of one tool-plugin on disk. A tool-plugin
3
+ * declares tools and ships an mcp/ directory (an mcpServers descriptor in the
4
+ * tool surface) — the plugins whose server must mount for their tools to be
5
+ * callable, whether admin- or specialist-facing. */
6
+ export interface ToolPluginManifestState {
7
+ manifestPresent: boolean;
8
+ hasMcpServers: boolean;
9
+ distPresent: boolean;
10
+ }
11
+ export interface ToolRegistrationDriftDefect {
12
+ accountId: string;
13
+ /** Tool-plugin dir name as it appears in account.json enabledPlugins. */
14
+ plugin: string;
15
+ /** The MCP server the mounted plugin would expose (== plugin dir name). */
16
+ expectedServer: string;
17
+ reason: ToolRegistrationDriftReason;
18
+ }
19
+ export interface ToolRegistrationDriftResult {
20
+ ok: boolean;
21
+ defects: ToolRegistrationDriftDefect[];
22
+ /** Count of (account, tool-plugin) pairs checked. */
23
+ inspected: number;
24
+ }
25
+ /** Classify one tool-plugin's manifest state into a drift reason, or null when
26
+ * the server would mount (manifest present, carries mcpServers, dist on disk). */
27
+ export declare function classifyToolRegistration(state: ToolPluginManifestState): ToolRegistrationDriftReason | null;
28
+ /** Cross-check each account's enabled tool-plugins against their generated
29
+ * manifests. `toolPlugins` maps a tool-plugin dir name to its on-disk manifest
30
+ * state; an enabledPlugins entry absent from that map is not a tool-plugin
31
+ * (platform non-tool plugin, skill-only premium sub, leaked foreign sub) and is
32
+ * out of scope here. */
33
+ export declare function assertToolRegistrationDrift(accounts: ReadonlyArray<{
34
+ accountId: string;
35
+ enabledPlugins: readonly string[];
36
+ }>, toolPlugins: ReadonlyMap<string, ToolPluginManifestState>): ToolRegistrationDriftResult;
37
+ /** Index plugin dirs across the roots, keyed by dir basename — the same key
38
+ * loadToolSurface and account.json enabledPlugins use. Platform plugins live at
39
+ * `<root>/<name>`; premium subs at `<premiumRoot>/<bundle>/plugins/<sub>`;
40
+ * standalone premium bundles at `<premiumRoot>/<bundle>`. */
41
+ export declare function indexPluginDirs(pluginRoots: readonly string[]): Map<string, string>;
42
+ /** Read the generated-manifest state of every named tool-plugin. A name with no
43
+ * dir on disk is reported as manifestPresent:false (→ not-installed), so a
44
+ * tool-plugin that vanished from disk is still surfaced rather than skipped. A
45
+ * present-but-corrupt manifest reads as manifestPresent:true, hasMcpServers:
46
+ * false (→ no-mcpServers-manifest).
47
+ *
48
+ * A tool-plugin whose `mcp:` server is a shared `platform/lib/<name>` binary
49
+ * rather than a plugin-local `mcp/` dir (e.g. `graph`, served by
50
+ * `platform/lib/graph-mcp`) is EXCLUDED from the result — the manifest
51
+ * generator only emits `mcpServers` for plugins that ship a plugin-local `mcp/`
52
+ * (its `hasMcp` predicate), so a shared-lib plugin's generated manifest carries
53
+ * no `mcpServers` by architecture, not by a `skip` flag. Judging it by the
54
+ * generated-manifest criterion would false-FATAL on every boot. This mirrors
55
+ * the generator's `hasMcp` check exactly. */
56
+ export declare function readToolPluginManifestStates(pluginRoots: readonly string[], toolPluginNames: Iterable<string>): Map<string, ToolPluginManifestState>;
57
+ //# sourceMappingURL=tool-registration-drift.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-registration-drift.d.ts","sourceRoot":"","sources":["../src/tool-registration-drift.ts"],"names":[],"mappings":"AAkBA,MAAM,MAAM,2BAA2B,GACnC,eAAe,GACf,wBAAwB,GACxB,cAAc,CAAA;AAElB;;;qDAGqD;AACrD,MAAM,WAAW,uBAAuB;IACtC,eAAe,EAAE,OAAO,CAAA;IACxB,aAAa,EAAE,OAAO,CAAA;IACtB,WAAW,EAAE,OAAO,CAAA;CACrB;AAED,MAAM,WAAW,2BAA2B;IAC1C,SAAS,EAAE,MAAM,CAAA;IACjB,yEAAyE;IACzE,MAAM,EAAE,MAAM,CAAA;IACd,2EAA2E;IAC3E,cAAc,EAAE,MAAM,CAAA;IACtB,MAAM,EAAE,2BAA2B,CAAA;CACpC;AAED,MAAM,WAAW,2BAA2B;IAC1C,EAAE,EAAE,OAAO,CAAA;IACX,OAAO,EAAE,2BAA2B,EAAE,CAAA;IACtC,qDAAqD;IACrD,SAAS,EAAE,MAAM,CAAA;CAClB;AAED;mFACmF;AACnF,wBAAgB,wBAAwB,CACtC,KAAK,EAAE,uBAAuB,GAC7B,2BAA2B,GAAG,IAAI,CAKpC;AAED;;;;yBAIyB;AACzB,wBAAgB,2BAA2B,CACzC,QAAQ,EAAE,aAAa,CAAC;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,cAAc,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,CAAC,EACjF,WAAW,EAAE,WAAW,CAAC,MAAM,EAAE,uBAAuB,CAAC,GACxD,2BAA2B,CAe7B;AAED;;;8DAG8D;AAC9D,wBAAgB,eAAe,CAAC,WAAW,EAAE,SAAS,MAAM,EAAE,GAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAkCnF;AAED;;;;;;;;;;;;;8CAa8C;AAC9C,wBAAgB,4BAA4B,CAC1C,WAAW,EAAE,SAAS,MAAM,EAAE,EAC9B,eAAe,EAAE,QAAQ,CAAC,MAAM,CAAC,GAChC,GAAG,CAAC,MAAM,EAAE,uBAAuB,CAAC,CAmCtC"}
@@ -0,0 +1,147 @@
1
+ // Boot-time tool-availability reconciliation. Maxy enables a tool-bearing plugin
2
+ // per account (account.json enabledPlugins) and the plugin's PLUGIN.md declares
3
+ // tools plus an `mcp:` block — but only the GENERATED `.claude-plugin/plugin.json`
4
+ // mcpServers block makes Claude Code spawn the server. A plugin on
5
+ // `mcp-manifest: skip` keeps its PLUGIN.md `mcp:` block (so the source-level
6
+ // `mcp-allowlist-without-server` gate passes) while the generator drops mcpServers
7
+ // from the artifact CC consumes — the server never mounts and every tool it owns
8
+ // is "listed but not live", silent until an operator complains. This module names
9
+ // that gap at manager boot.
10
+ //
11
+ // Twin of skill-registration-drift.ts (which does the same for a sub-plugin's
12
+ // SKILLS). Like that check this one does NOT refuse boot — an unmounted
13
+ // tool-plugin must not brick the whole install; the manager logs a standing
14
+ // FATAL line per defect and continues (Task 1574).
15
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+ /** Classify one tool-plugin's manifest state into a drift reason, or null when
18
+ * the server would mount (manifest present, carries mcpServers, dist on disk). */
19
+ export function classifyToolRegistration(state) {
20
+ if (!state.manifestPresent)
21
+ return 'not-installed';
22
+ if (!state.hasMcpServers)
23
+ return 'no-mcpServers-manifest';
24
+ if (!state.distPresent)
25
+ return 'dist-missing';
26
+ return null;
27
+ }
28
+ /** Cross-check each account's enabled tool-plugins against their generated
29
+ * manifests. `toolPlugins` maps a tool-plugin dir name to its on-disk manifest
30
+ * state; an enabledPlugins entry absent from that map is not a tool-plugin
31
+ * (platform non-tool plugin, skill-only premium sub, leaked foreign sub) and is
32
+ * out of scope here. */
33
+ export function assertToolRegistrationDrift(accounts, toolPlugins) {
34
+ const defects = [];
35
+ let inspected = 0;
36
+ for (const account of accounts) {
37
+ for (const plugin of account.enabledPlugins) {
38
+ const state = toolPlugins.get(plugin);
39
+ if (!state)
40
+ continue; // not a tool-plugin on disk — out of scope
41
+ inspected += 1;
42
+ const reason = classifyToolRegistration(state);
43
+ if (reason) {
44
+ defects.push({ accountId: account.accountId, plugin, expectedServer: plugin, reason });
45
+ }
46
+ }
47
+ }
48
+ return { ok: defects.length === 0, defects, inspected };
49
+ }
50
+ /** Index plugin dirs across the roots, keyed by dir basename — the same key
51
+ * loadToolSurface and account.json enabledPlugins use. Platform plugins live at
52
+ * `<root>/<name>`; premium subs at `<premiumRoot>/<bundle>/plugins/<sub>`;
53
+ * standalone premium bundles at `<premiumRoot>/<bundle>`. */
54
+ export function indexPluginDirs(pluginRoots) {
55
+ const out = new Map();
56
+ const addIfPlugin = (name, dir) => {
57
+ if (name.startsWith('.'))
58
+ return;
59
+ try {
60
+ if (!statSync(dir).isDirectory())
61
+ return;
62
+ }
63
+ catch {
64
+ return;
65
+ }
66
+ if (existsSync(join(dir, 'PLUGIN.md')))
67
+ out.set(name, dir);
68
+ };
69
+ for (const root of pluginRoots) {
70
+ let entries;
71
+ try {
72
+ entries = readdirSync(root);
73
+ }
74
+ catch {
75
+ continue;
76
+ }
77
+ for (const name of entries) {
78
+ const dir = join(root, name);
79
+ addIfPlugin(name, dir); // platform plugin / standalone premium bundle
80
+ const subDir = join(dir, 'plugins'); // premium bundle subs
81
+ if (existsSync(subDir)) {
82
+ let subs;
83
+ try {
84
+ subs = readdirSync(subDir);
85
+ }
86
+ catch {
87
+ subs = [];
88
+ }
89
+ for (const sub of subs)
90
+ addIfPlugin(sub, join(subDir, sub));
91
+ }
92
+ }
93
+ }
94
+ return out;
95
+ }
96
+ /** Read the generated-manifest state of every named tool-plugin. A name with no
97
+ * dir on disk is reported as manifestPresent:false (→ not-installed), so a
98
+ * tool-plugin that vanished from disk is still surfaced rather than skipped. A
99
+ * present-but-corrupt manifest reads as manifestPresent:true, hasMcpServers:
100
+ * false (→ no-mcpServers-manifest).
101
+ *
102
+ * A tool-plugin whose `mcp:` server is a shared `platform/lib/<name>` binary
103
+ * rather than a plugin-local `mcp/` dir (e.g. `graph`, served by
104
+ * `platform/lib/graph-mcp`) is EXCLUDED from the result — the manifest
105
+ * generator only emits `mcpServers` for plugins that ship a plugin-local `mcp/`
106
+ * (its `hasMcp` predicate), so a shared-lib plugin's generated manifest carries
107
+ * no `mcpServers` by architecture, not by a `skip` flag. Judging it by the
108
+ * generated-manifest criterion would false-FATAL on every boot. This mirrors
109
+ * the generator's `hasMcp` check exactly. */
110
+ export function readToolPluginManifestStates(pluginRoots, toolPluginNames) {
111
+ const dirs = indexPluginDirs(pluginRoots);
112
+ const out = new Map();
113
+ for (const name of toolPluginNames) {
114
+ const dir = dirs.get(name);
115
+ if (!dir) {
116
+ out.set(name, { manifestPresent: false, hasMcpServers: false, distPresent: false });
117
+ continue;
118
+ }
119
+ // Mirror generate-plugin-manifests.mjs `hasMcp`: only a plugin-local mcp/
120
+ // dir yields a generated mcpServers block. Shared-lib-server plugins are a
121
+ // different mount architecture, out of this gate's remit.
122
+ const hasLocalMcp = existsSync(join(dir, 'mcp', 'dist', 'index.js')) ||
123
+ existsSync(join(dir, 'mcp', 'package.json'));
124
+ if (!hasLocalMcp)
125
+ continue;
126
+ const manifestPath = join(dir, '.claude-plugin', 'plugin.json');
127
+ const manifestPresent = existsSync(manifestPath);
128
+ let hasMcpServers = false;
129
+ if (manifestPresent) {
130
+ try {
131
+ const parsed = JSON.parse(readFileSync(manifestPath, 'utf-8'));
132
+ hasMcpServers =
133
+ !!parsed.mcpServers &&
134
+ typeof parsed.mcpServers === 'object' &&
135
+ !Array.isArray(parsed.mcpServers) &&
136
+ Object.keys(parsed.mcpServers).length > 0;
137
+ }
138
+ catch {
139
+ /* corrupt manifest → hasMcpServers stays false → no-mcpServers-manifest */
140
+ }
141
+ }
142
+ const distPresent = existsSync(join(dir, 'mcp', 'dist', 'index.js'));
143
+ out.set(name, { manifestPresent, hasMcpServers, distPresent });
144
+ }
145
+ return out;
146
+ }
147
+ //# sourceMappingURL=tool-registration-drift.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-registration-drift.js","sourceRoot":"","sources":["../src/tool-registration-drift.ts"],"names":[],"mappings":"AAAA,iFAAiF;AACjF,gFAAgF;AAChF,mFAAmF;AACnF,mEAAmE;AACnE,6EAA6E;AAC7E,mFAAmF;AACnF,iFAAiF;AACjF,kFAAkF;AAClF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,CAAA;gBAC1F,aAAa;oBACX,CAAC,CAAC,MAAM,CAAC,UAAU;wBACnB,OAAO,MAAM,CAAC,UAAU,KAAK,QAAQ;wBACrC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC;wBACjC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,UAAqC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAA;YACxE,CAAC;YAAC,MAAM,CAAC;gBACP,2EAA2E;YAC7E,CAAC;QACH,CAAC;QACD,MAAM,WAAW,GAAG,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC,CAAA;QACpE,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,eAAe,EAAE,aAAa,EAAE,WAAW,EAAE,CAAC,CAAA;IAChE,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC"}
@@ -4,5 +4,18 @@
4
4
  "version": "0.1.0",
5
5
  "author": {
6
6
  "name": "Rubytech LLC"
7
+ },
8
+ "mcpServers": {
9
+ "sitedesk-job": {
10
+ "type": "stdio",
11
+ "command": "node",
12
+ "args": [
13
+ "${CLAUDE_PLUGIN_ROOT}/lib/mcp-spawn-tee/index.js",
14
+ "${CLAUDE_PLUGIN_ROOT}/mcp/dist/index.js"
15
+ ],
16
+ "env": {
17
+ "MCP_SPAWN_TEE_NAME": "sitedesk-job"
18
+ }
19
+ }
7
20
  }
8
21
  }
@@ -12,7 +12,7 @@ mcp:
12
12
  PLATFORM_ROOT: ${PLATFORM_ROOT}
13
13
  ACCOUNT_ID: ${ACCOUNT_ID}
14
14
  SESSION_ID: ${SESSION_ID}
15
- mcp-manifest: skip
15
+ mcp-manifest: auto
16
16
  tools:
17
17
  - name: quote-engine-run
18
18
  publicAllowlist: false
@@ -0,0 +1,193 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /**
4
+ * MCP spawn-tee — in-process stderr capture + lifecycle observability.
5
+ *
6
+ * Claude Code spawns each MCP server itself; the platform never holds a
7
+ * ChildProcess handle. This shim sits between Claude Code and the real MCP
8
+ * server: Claude Code runs `node <this> <real-entry>`, and the shim runs the
9
+ * real entry IN ITS OWN PROCESS via dynamic import() — one node runtime, not
10
+ * two. Before importing, it replaces process.stderr.write with a tee so every
11
+ * stderr byte the server writes is mirrored to the log sinks; stdin and stdout
12
+ * (the JSON-RPC channel) are never touched.
13
+ *
14
+ * Claude Code CLI → shim (this file) = node running <real-entry> in-process
15
+ * stdin/stdout : untouched (JSON-RPC channel)
16
+ * stderr : process.stderr.write teed → per-date + per-session + passthrough
17
+ *
18
+ * Destinations (Task 706) — unchanged:
19
+ * - `${LOG_DIR}/mcp-<name>-stderr-<date>.log` — per-date raw (back-compat;
20
+ * the in-process mcp-stderr-tee and the [mcp-init-error] probe read it).
21
+ * - `${LOG_DIR}/mcp-<name>-<SESSION_ID>.log` — per-session raw + lifecycle
22
+ * lines. Authoritative sink. Absent when SESSION_ID is unset (enumeration
23
+ * spawn) — then the per-date file is the fallback.
24
+ * - `server.log` via the loopback log-ingest route — best-effort mirror of
25
+ * the [mcp-helper] lifecycle lines.
26
+ *
27
+ * Lifecycle lines, correlation key `session=<id8> server=<name>` — unchanged:
28
+ * [mcp-helper] op=spawn ... pid= entry=
29
+ * [mcp-helper] op=boot ... head=<first stderr bytes>
30
+ * [mcp-helper] op=exit ... code= signal= lifetimeMs= stderr-tail=
31
+ *
32
+ * Process model (Task 989): the shim IS the server's process. op=exit fires
33
+ * from process.on("exit"), so it covers a normal exit, a non-zero exit, an
34
+ * uncaught throw (code 1), and a catchable-signal exit (SIGTERM/SIGINT/SIGHUP,
35
+ * whose handlers record the signal name). An external SIGKILL is uncatchable
36
+ * and leaves no op=exit line — the per-session stderr tail already on disk and
37
+ * Claude Code's own transport-drop are the evidence for that death mode.
38
+ *
39
+ * The shim never writes to fd 1 (stdout) — that is the JSON-RPC channel.
40
+ */
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ const node_fs_1 = require("node:fs");
43
+ const node_path_1 = require("node:path");
44
+ const node_url_1 = require("node:url");
45
+ const SERVER_NAME = process.env.MCP_SPAWN_TEE_NAME ?? "unknown";
46
+ const LOG_DIR = process.env.LOG_DIR;
47
+ const SESSION_ID = process.env.SESSION_ID;
48
+ const PLATFORM_PORT = process.env.PLATFORM_PORT;
49
+ const ENTRY = process.argv[2];
50
+ const SESSION_ID8 = SESSION_ID ? SESSION_ID.slice(0, 8) : "—";
51
+ const spawnStamp = Date.now();
52
+ // Per-session raw + lifecycle log (Task 706). Empty SESSION_ID (enumeration
53
+ // spawn) → undefined, and the per-date file is the fallback.
54
+ const perSessionPath = LOG_DIR && SESSION_ID
55
+ ? (0, node_path_1.resolve)(LOG_DIR, `mcp-${SERVER_NAME}-${SESSION_ID}.log`)
56
+ : undefined;
57
+ const perDatePath = LOG_DIR
58
+ ? (0, node_path_1.resolve)(LOG_DIR, `mcp-${SERVER_NAME}-stderr-${new Date(spawnStamp).toISOString().slice(0, 10)}.log`)
59
+ : undefined;
60
+ // Rolling tail of entry stderr for op=exit. Capped so a chatty server cannot
61
+ // grow the buffer without bound.
62
+ const TAIL_CAP = 2048;
63
+ let stderrTail = "";
64
+ let bootEmitted = false;
65
+ let exitEmitted = false;
66
+ let exitSignal;
67
+ // The real stderr writer, captured before the tee replaces it. Lifecycle lines
68
+ // and stderr passthrough both go through this so they are never re-teed into
69
+ // the per-date sink nor recursed back into the patched writer.
70
+ const rawStderrWrite = process.stderr.write.bind(process.stderr);
71
+ // LOG_DIR is created once, lazily, on the first successful append — not per
72
+ // chunk. teeWrite runs on the server's own stderr hot path now, so a per-call
73
+ // mkdirSync would be two syscalls per log line for nothing.
74
+ let logDirReady = false;
75
+ function appendSafe(path, data) {
76
+ if (!path || !LOG_DIR)
77
+ return;
78
+ try {
79
+ if (!logDirReady) {
80
+ (0, node_fs_1.mkdirSync)(LOG_DIR, { recursive: true });
81
+ logDirReady = true;
82
+ }
83
+ (0, node_fs_1.appendFileSync)(path, data);
84
+ }
85
+ catch {
86
+ /* unwritable destination — never mask primary output */
87
+ }
88
+ }
89
+ // Best-effort mirror of a lifecycle line to server.log via the loopback
90
+ // log-ingest route. Fire-and-forget: the per-session file is authoritative, so
91
+ // a dropped POST loses nothing. On the "exit" event the loop is stopping, so
92
+ // the op=exit mirror may not flush — the per-session line, written sync, holds.
93
+ function postToServerLog(suffix, level) {
94
+ if (!PLATFORM_PORT)
95
+ return;
96
+ try {
97
+ const ctrl = new AbortController();
98
+ const t = setTimeout(() => ctrl.abort(), 500);
99
+ t.unref?.(); // never let the abort timer keep the shim's event loop alive
100
+ void fetch(`http://127.0.0.1:${PLATFORM_PORT}/api/admin/log-ingest`, {
101
+ method: "POST",
102
+ headers: { "content-type": "application/json" },
103
+ body: JSON.stringify({ tag: "mcp-helper", level, line: suffix }),
104
+ signal: ctrl.signal,
105
+ }).then(() => clearTimeout(t)).catch(() => clearTimeout(t));
106
+ }
107
+ catch {
108
+ /* fetch threw synchronously — best-effort only */
109
+ }
110
+ }
111
+ // Emit one [mcp-helper] lifecycle line: authoritative per-session file (sync,
112
+ // survives process.exit), the shim's own stderr via the RAW writer (journald /
113
+ // Claude Code visibility, never re-teed), and a best-effort server.log mirror.
114
+ // `suffix` is the line body after the tag and carries no newline (the
115
+ // log-ingest route rejects newlines).
116
+ function emitLifecycle(suffix, level) {
117
+ const line = `[mcp-helper] ${suffix}\n`;
118
+ appendSafe(perSessionPath, line);
119
+ try {
120
+ rawStderrWrite(line);
121
+ }
122
+ catch { /* stderr closed */ }
123
+ postToServerLog(suffix, level);
124
+ }
125
+ if (!ENTRY) {
126
+ emitLifecycle(`op=error session=${SESSION_ID8} server=${SERVER_NAME} reason="no entry given (argv[2] missing)"`, "error");
127
+ process.exit(2);
128
+ }
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) => {
133
+ const chunk = args[0];
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(...args); // passthrough
144
+ });
145
+ process.stderr.write = teeWrite;
146
+ // Catchable-signal handling. The shim drives the exit ONLY when it is the sole
147
+ // listener for the signal — i.e. the imported entry installed no handler of its
148
+ // own. In that case it records the signal (so op=exit carries signal=<sig>) and
149
+ // exits with 128+signum, mirroring the prior wrapper's exit-status convention.
150
+ //
151
+ // When the entry DID install a handler, the shim defers entirely and records
152
+ // nothing: the entry's handler decides the exit code, and op=exit reflects that
153
+ // exit verbatim. This matches the prior two-process model, where a child that
154
+ // caught the signal and exited cleanly was observed as code=0 signal=— (a clean
155
+ // self-exit), not as a signal death. Setting exitSignal here unconditionally
156
+ // would mislabel every graceful signal-driven shutdown as a signal kill.
157
+ function onSignal(sig, code) {
158
+ return () => {
159
+ if (process.listenerCount(sig) === 1) {
160
+ exitSignal = sig;
161
+ process.exit(code);
162
+ }
163
+ };
164
+ }
165
+ process.on("SIGTERM", onSignal("SIGTERM", 143));
166
+ process.on("SIGINT", onSignal("SIGINT", 130));
167
+ process.on("SIGHUP", onSignal("SIGHUP", 129));
168
+ // op=exit, emitted once from the process "exit" event. Sync-only — the loop is
169
+ // stopping. When a catchable signal caused the exit, report code=— signal=<sig>
170
+ // to match the prior wrapper's format; otherwise code=<exit code> signal=—.
171
+ process.on("exit", (code) => {
172
+ if (exitEmitted)
173
+ return;
174
+ exitEmitted = true;
175
+ const lifetimeMs = Date.now() - spawnStamp;
176
+ const tail = stderrTail.slice(-200);
177
+ const codeField = exitSignal ? "—" : String(code);
178
+ const level = exitSignal || code !== 0 ? "error" : "info";
179
+ emitLifecycle(`op=exit session=${SESSION_ID8} server=${SERVER_NAME} pid=${process.pid} ` +
180
+ `code=${codeField} signal=${exitSignal ?? "—"} lifetimeMs=${lifetimeMs} stderr-tail=${JSON.stringify(tail)}`, level);
181
+ });
182
+ emitLifecycle(`op=spawn session=${SESSION_ID8} server=${SERVER_NAME} pid=${process.pid} entry=${ENTRY}`, "info");
183
+ // Run the real MCP server in THIS process. Dynamic import() (not top-level
184
+ // await — this file compiles to CommonJS) loads the ESM entry; a load-time
185
+ // failure mirrors the old child spawn-error path (op=error, exit 127). The
186
+ // op=exit handler is suppressed on this path so op=error stays the sole record.
187
+ import((0, node_url_1.pathToFileURL)(ENTRY).href).catch((err) => {
188
+ const msg = err instanceof Error ? err.message : String(err);
189
+ exitEmitted = true;
190
+ emitLifecycle(`op=error session=${SESSION_ID8} server=${SERVER_NAME} reason=${JSON.stringify(`import error: ${msg}`)}`, "error");
191
+ process.exit(127);
192
+ });
193
+ //# sourceMappingURL=index.js.map