@uniqbit/mate-core 0.15.3 → 0.15.4-canary.10

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 (94) hide show
  1. package/claude-plugin/.claude-plugin/plugin.json +4 -0
  2. package/claude-plugin/hooks/artifact-finish-nudge.mjs +8 -0
  3. package/claude-plugin/hooks/hooks.json +37 -0
  4. package/claude-plugin/hooks/session-banner.mjs +8 -0
  5. package/claude-plugin/hooks/ts-loader.mjs +28 -0
  6. package/claude-plugin/hooks/validate-artifact-path.mjs +8 -0
  7. package/package.json +4 -2
  8. package/src/cli/commands/artifact/finish/openspec.ts +1 -5
  9. package/src/cli/commands/companion/hub.ts +99 -0
  10. package/src/cli/commands/companion/link.ts +0 -5
  11. package/src/cli/commands/companion/tui.ts +3 -2
  12. package/src/cli/commands/doctor.ts +254 -170
  13. package/src/cli/commands/install.ts +18 -14
  14. package/src/cli/commands/launch/shared.ts +4 -4
  15. package/src/cli/commands/plugin/install.ts +94 -0
  16. package/src/cli/commands/plugin/plugin.ts +17 -0
  17. package/src/cli/commands/setup.ts +4 -6
  18. package/src/cli/commands/update.ts +9 -11
  19. package/src/cli/companion-link-wizard.tsx +22 -78
  20. package/src/cli/main.ts +57 -13
  21. package/src/cli/plugin-commands.ts +4 -4
  22. package/src/cli/repo-list-table.tsx +2 -7
  23. package/src/cli/usage.ts +7 -3
  24. package/src/distribution.ts +3 -5
  25. package/src/framework.ts +4 -36
  26. package/src/hooks/artifact-finish-nudge.ts +212 -0
  27. package/src/hooks/session-banner.ts +25 -0
  28. package/src/hooks/validate-artifact-path.ts +236 -0
  29. package/src/index.ts +4 -0
  30. package/src/lib/context-mode-package.ts +5 -3
  31. package/src/lib/install.ts +31 -43
  32. package/src/lib/orchestrator/adapters/base.ts +7 -8
  33. package/src/lib/orchestrator/adapters/claude.ts +16 -0
  34. package/src/lib/orchestrator/adapters/opencode.ts +10 -60
  35. package/src/lib/orchestrator/companion-hub.ts +380 -0
  36. package/src/lib/orchestrator/companion-store.ts +1 -35
  37. package/src/lib/orchestrator/config-store.ts +94 -7
  38. package/src/lib/orchestrator/editor.ts +4 -20
  39. package/src/lib/orchestrator/framework-context.ts +119 -24
  40. package/src/lib/orchestrator/global-config-store.ts +1 -5
  41. package/src/lib/orchestrator/launcher.ts +3 -9
  42. package/src/lib/orchestrator/migration.ts +0 -23
  43. package/src/lib/orchestrator/opencode-guidance.ts +1 -2
  44. package/src/lib/orchestrator/repo-local-registry.ts +3 -1
  45. package/src/lib/orchestrator/root-context.ts +117 -0
  46. package/src/lib/orchestrator/setup-compatibilities.ts +1 -1
  47. package/src/lib/orchestrator/setup-preflight.ts +5 -18
  48. package/src/lib/orchestrator/types.ts +27 -19
  49. package/src/lib/orchestrator/working-repo-store.ts +9 -3
  50. package/src/lib/package-paths.ts +37 -0
  51. package/src/lib/update-checker.ts +5 -5
  52. package/src/playbooks/companion-guidance.ts +7 -7
  53. package/src/runtime/env.ts +0 -4
  54. package/src/templates/capabilities/openspec-cap/mate-skills/{mate-artifact-finish → agents/mate-artifact-finish}/SKILL.md +8 -8
  55. package/src/templates/capabilities/openspec-cap/mate-skills/{mate-artifact-finish → agents/mate-artifact-finish}/references/openspec.md +3 -3
  56. package/src/templates/capabilities/openspec-cap/mate-skills/claude/mate-artifact-finish/SKILL.md +58 -0
  57. package/src/templates/capabilities/openspec-cap/mate-skills/claude/mate-artifact-finish/references/openspec.md +139 -0
  58. package/src/templates/capabilities/openspec-cap/mate-v1/schema.yaml +6 -5
  59. package/src/templates/root/TEMPLATE_AGENTS.md +2 -0
  60. package/src/templates/root/TEMPLATE_CLAUDE.md +2 -0
  61. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +3541 -0
  62. package/src/tools/setup/capabilities/context-mode.ts +57 -83
  63. package/src/tools/setup/capabilities/graphify-shared.ts +27 -0
  64. package/src/tools/setup/capabilities/graphify.ts +86 -295
  65. package/src/tools/setup/capabilities/openspec.ts +27 -30
  66. package/src/tools/setup/capabilities/react-doctor.ts +37 -37
  67. package/src/tools/setup/capabilities/rtk.ts +4 -1
  68. package/src/tools/setup/capabilities/tokensave-shared.ts +6 -0
  69. package/src/tools/setup/capabilities/tokensave.ts +50 -71
  70. package/src/tools/setup/context-services.ts +29 -0
  71. package/src/tools/setup/dynamic-plugins/host.ts +2 -1
  72. package/src/tools/setup/dynamic-plugins/hydrate.ts +3 -13
  73. package/src/tools/setup/dynamic-plugins/install.ts +124 -109
  74. package/src/tools/setup/dynamic-plugins/loader.ts +23 -58
  75. package/src/tools/setup/dynamic-plugins/paths.ts +8 -19
  76. package/src/tools/setup/dynamic-plugins/registry-hint.ts +14 -0
  77. package/src/tools/setup/engine.ts +65 -1
  78. package/src/tools/setup/mate.ts +28 -31
  79. package/src/tools/setup/plugin.ts +81 -0
  80. package/src/tools/setup/plugins/gitignore.ts +19 -9
  81. package/src/tools/setup/plugins/guidance.ts +2 -6
  82. package/src/tools/setup/policy.ts +4 -7
  83. package/src/tools/setup/providers/agent-file-sections.ts +78 -0
  84. package/src/tools/setup/providers/claude-format.ts +159 -0
  85. package/src/tools/setup/providers/claude.ts +283 -292
  86. package/src/tools/setup/providers/opencode-format.ts +146 -0
  87. package/src/tools/setup/providers/opencode.ts +171 -66
  88. package/src/tools/setup/providers/skill-tree.ts +38 -0
  89. package/src/tools/setup.ts +12 -7
  90. package/src/tui.ts +5 -0
  91. package/src/templates/capabilities/openspec-cap/claude/hooks/mate-artifact-finish.sh +0 -161
  92. package/src/templates/providers/claude/.claude/hooks/mate-session-banner +0 -28
  93. package/src/templates/providers/claude/.claude/hooks/validate-artifact-path +0 -242
  94. package/src/tools/setup/dynamic-plugins/pin-store.ts +0 -30
@@ -1,7 +1,7 @@
1
1
  import type { PluginRegistry } from "./tools/setup/registry";
2
2
 
3
3
  export interface DistributionUpdateConfig {
4
- /** npm package whose versions are checked and installed by `mate update`. Defaults to `@uniqbit/<name>`. */
4
+ /** npm package whose versions are checked and installed by `mate update`. Defaults to `@uniqbit/mate`. */
5
5
  packageName?: string;
6
6
  /** npm registry used for update checks and downloads. Defaults to public npm. */
7
7
  registry?: string;
@@ -14,15 +14,13 @@ export interface DistributionUpdateConfig {
14
14
  enforce?: boolean;
15
15
  }
16
16
 
17
- /** Identity and version of the distribution assembled through `createMate`. */
17
+ /** Version and plugin registry of the distribution assembled through `createMate`. */
18
18
  export interface DistributionConfig {
19
- name: string;
20
- legacyNames?: string[];
21
19
  runtime: "bun";
22
20
  version: string;
23
21
  /** Asset directories that override the framework defaults, highest precedence first. */
24
22
  assetRoots?: string[];
25
- /** Optional update source; defaults to `@uniqbit/<name>` on public npm. */
23
+ /** Optional update source; defaults to `@uniqbit/mate` on public npm. */
26
24
  update?: DistributionUpdateConfig;
27
25
  }
28
26
 
package/src/framework.ts CHANGED
@@ -1,39 +1,7 @@
1
- import { getActiveDistribution } from "./distribution";
2
-
3
1
  /**
4
- * Framework identity: names everything identity-shaped regardless of how the
5
- * CLI is invoked — state directories (`~/.mate`, `.mate/`), managed-block
6
- * markers, `MATE_*` env values, and the `companion-policy framework`
7
- * attribute. A whitelabel distribution changes the invocation name only;
8
- * identity stays `mate`. Use `frameworkCommandName()` for anything the user
9
- * or an agent types.
2
+ * Framework identity: names everything identity-shaped — state directories
3
+ * (`~/.mate`, `.mate/`), managed-block markers, `MATE_*` env values, usage
4
+ * output, command hints, error prefixes, agent guidance, and permission
5
+ * entries. The distribution is always invoked as `mate`.
10
6
  */
11
7
  export const FRAMEWORK_NAME = "mate";
12
-
13
- /**
14
- * Invocation name: how this distribution's CLI is invoked, derived from the
15
- * package's `bin` key (`config.name`). Drives usage output, command hints,
16
- * error prefixes, agent guidance, and permission entries — never paths,
17
- * markers, or env values (use `FRAMEWORK_NAME` for those).
18
- */
19
- export function frameworkCommandName(): string {
20
- return getActiveDistribution().config.name;
21
- }
22
-
23
- /**
24
- * Live view of the active distribution's identity. Framework modules read
25
- * identity through this object; the values always come from the config the
26
- * distribution passed to `createMate` — the framework itself carries no
27
- * hardcoded distribution name.
28
- */
29
- export const frameworkConfig = {
30
- get name(): string {
31
- return getActiveDistribution().config.name;
32
- },
33
- get legacyNames(): string[] {
34
- return getActiveDistribution().config.legacyNames ?? [];
35
- },
36
- get runtime(): string {
37
- return getActiveDistribution().config.runtime;
38
- },
39
- };
@@ -0,0 +1,212 @@
1
+ // Nudge the agent into the mate-artifact-finish workflow after a Bash command
2
+ // visibly archived an OpenSpec change. Stateless PostToolUse hook: never denies
3
+ // or blocks; emits additionalContext only on apparent success.
4
+ import type { HookEnv } from "./validate-artifact-path";
5
+
6
+ export interface NudgeOutcome {
7
+ exitCode: number;
8
+ stdout: string;
9
+ }
10
+
11
+ const ARCHIVE_PATH_PATTERN =
12
+ /(?:^|[\s/"'`,(])openspec\/changes\/archive\/(\d{4}-\d{2}-\d{2}-[^/\s"'`,)]+)/;
13
+
14
+ // The nudge only applies when the openspec capability is enabled and OpenSpec
15
+ // git auto mode is on; the plugin registers the hook unconditionally, so the
16
+ // gate is evaluated here from launch-injected environment before any parsing.
17
+ export function isGateEnabled(env: HookEnv): boolean {
18
+ return env.MATE_OPENSPEC_ENABLED === "1" && env.MATE_GIT_AUTO_MODE === "1";
19
+ }
20
+
21
+ export function shellSplit(command: string): string[] {
22
+ const parts: string[] = [];
23
+ let current = "";
24
+ let quote: string | null = null;
25
+ let escaping = false;
26
+ for (let index = 0; index < command.length; index += 1) {
27
+ const char = command[index];
28
+ if (escaping) {
29
+ current += char;
30
+ escaping = false;
31
+ continue;
32
+ }
33
+ if (char === "\\" && quote !== "'") {
34
+ const next = command[index + 1] || "";
35
+ if (next === "\\" || /\s/.test(next) || next === "'" || next === '"') {
36
+ escaping = true;
37
+ continue;
38
+ }
39
+ }
40
+ if ((char === "'" || char === '"') && !quote) {
41
+ quote = char;
42
+ continue;
43
+ }
44
+ if (quote === char) {
45
+ quote = null;
46
+ continue;
47
+ }
48
+ const next = command[index + 1] || "";
49
+ const previous = command[index - 1] || "";
50
+ const isControlOperator =
51
+ !quote &&
52
+ (char === ";" ||
53
+ char === "|" ||
54
+ (char === "&" && next !== ">" && previous !== ">" && previous !== "<"));
55
+ if (isControlOperator) {
56
+ if (current) parts.push(current);
57
+ current = "";
58
+ if ((char === "|" || char === "&") && next === char) {
59
+ parts.push(char + next);
60
+ index += 1;
61
+ } else {
62
+ parts.push(char);
63
+ }
64
+ continue;
65
+ }
66
+ if (!quote && /\s/.test(char)) {
67
+ if (current) parts.push(current);
68
+ current = "";
69
+ continue;
70
+ }
71
+ current += char;
72
+ }
73
+ if (current) parts.push(current);
74
+ return parts;
75
+ }
76
+
77
+ function extractChangeFromPath(value: string): string | null {
78
+ const match = value.replaceAll("\\", "/").match(ARCHIVE_PATH_PATTERN);
79
+ return match ? match[1].replace(/^\d{4}-\d{2}-\d{2}-/, "") : null;
80
+ }
81
+
82
+ // Shell syntax tokens are never change-name positionals: separators end the
83
+ // archive invocation, redirections are skipped (a bare operator also consumes
84
+ // its target token).
85
+ const SEPARATOR_PATTERN = /^(\|\|?|&&?|;)$/;
86
+ const REDIRECTION_PATTERN = /^(\d*(>>?|<)|&>>?)/;
87
+ const BARE_REDIRECTION_PATTERN = /^(\d*(>>?|<)|&>>?)$/;
88
+
89
+ export function extractArchiveCommand(command: string): string | null {
90
+ const parts = shellSplit(command);
91
+ const index = parts.findIndex(
92
+ (part, position) =>
93
+ part === "archive" &&
94
+ position > 0 &&
95
+ (parts[position - 1] === "openspec" || parts[position - 1].endsWith("/openspec")),
96
+ );
97
+ if (index < 0) return null;
98
+ for (let position = index + 1; position < parts.length; position += 1) {
99
+ const part = parts[position];
100
+ if (!part || part === "--") continue;
101
+ if (SEPARATOR_PATTERN.test(part)) return null;
102
+ if (REDIRECTION_PATTERN.test(part)) {
103
+ if (BARE_REDIRECTION_PATTERN.test(part)) position += 1;
104
+ continue;
105
+ }
106
+ if (part.startsWith("-")) {
107
+ if (part === "--store") position += 1;
108
+ continue;
109
+ }
110
+ return part;
111
+ }
112
+ return null;
113
+ }
114
+
115
+ const MOVE_COMMANDS = new Set([
116
+ "mv",
117
+ "move",
118
+ "move-item",
119
+ "cmd",
120
+ "cmd.exe",
121
+ "powershell",
122
+ "powershell.exe",
123
+ "pwsh",
124
+ "pwsh.exe",
125
+ ]);
126
+
127
+ function isPython(part: string): boolean {
128
+ return /^python(?:\d(?:\.\d+)*)?(?:\.exe)?$/i.test(part.split(/[\\/]/).pop() || part);
129
+ }
130
+
131
+ export function extractMoveCommand(command: string): string | null {
132
+ const parts = shellSplit(command);
133
+ for (let index = 0; index < parts.length; index += 1) {
134
+ if (MOVE_COMMANDS.has(parts[index].toLowerCase())) {
135
+ for (const part of parts.slice(index + 1)) {
136
+ const change = extractChangeFromPath(part);
137
+ if (change) return change;
138
+ }
139
+ }
140
+ if (isPython(parts[index]) && /(?:shutil\.move|os\.rename|\.rename\s*\()/.test(command)) {
141
+ return extractChangeFromPath(command);
142
+ }
143
+ }
144
+ return null;
145
+ }
146
+
147
+ // Nudge only on apparent success: stay silent on a clear failure indication,
148
+ // nudge when success is indicated or indeterminate.
149
+ export function isClearFailure(response: unknown): boolean {
150
+ if (!response || typeof response !== "object") return false;
151
+ const value = response as Record<string, unknown>;
152
+ if (value.success === false || value.is_error === true) return true;
153
+ if (typeof value.error === "string" && value.error) return true;
154
+ if (value.interrupted === true) return true;
155
+ const exitCode = value.exit_code ?? value.exitCode;
156
+ return typeof exitCode === "number" && exitCode !== 0;
157
+ }
158
+
159
+ export function evaluate(payload: unknown, env: HookEnv): NudgeOutcome {
160
+ const silent: NudgeOutcome = { exitCode: 0, stdout: "" };
161
+ if (!isGateEnabled(env)) return silent;
162
+
163
+ const input = payload && typeof payload === "object" ? (payload as Record<string, unknown>) : {};
164
+ if (input.hook_event_name !== "PostToolUse" || input.tool_name !== "Bash") return silent;
165
+
166
+ const toolInput =
167
+ input.tool_input && typeof input.tool_input === "object"
168
+ ? (input.tool_input as Record<string, unknown>)
169
+ : {};
170
+ const command = typeof toolInput.command === "string" ? toolInput.command : "";
171
+ const change = extractArchiveCommand(command) || extractMoveCommand(command);
172
+ if (!change) return silent;
173
+ if (isClearFailure(input.tool_response)) return silent;
174
+
175
+ const context =
176
+ `OpenSpec change ${change} was just archived. Invoke the mate-artifact-finish ` +
177
+ `skill, then run \`mate artifact finish "${change}" --json\` to complete the ` +
178
+ "finish workflow (commit, tag, and push).";
179
+ return {
180
+ exitCode: 0,
181
+ stdout: JSON.stringify({
182
+ hookSpecificOutput: {
183
+ hookEventName: "PostToolUse",
184
+ additionalContext: context,
185
+ },
186
+ }),
187
+ };
188
+ }
189
+
190
+ async function readStdin(): Promise<string> {
191
+ const chunks: Buffer[] = [];
192
+ for await (const chunk of process.stdin) {
193
+ chunks.push(Buffer.from(chunk));
194
+ }
195
+ return Buffer.concat(chunks).toString("utf8");
196
+ }
197
+
198
+ // Plugin-shim entry. The gate check precedes stdin parsing so a disabled gate
199
+ // costs one env read.
200
+ export async function run(): Promise<number> {
201
+ if (!isGateEnabled(process.env)) return 0;
202
+
203
+ let payload: unknown = {};
204
+ try {
205
+ payload = JSON.parse(await readStdin());
206
+ } catch {
207
+ payload = {};
208
+ }
209
+ const outcome = evaluate(payload, process.env);
210
+ if (outcome.stdout) process.stdout.write(outcome.stdout);
211
+ return outcome.exitCode;
212
+ }
@@ -0,0 +1,25 @@
1
+ // Show the active Mate companion paths in Claude Code.
2
+ import type { HookEnv } from "./validate-artifact-path";
3
+
4
+ export interface BannerOutcome {
5
+ exitCode: number;
6
+ stdout: string;
7
+ }
8
+
9
+ // Fail-soft outside managed sessions: no MATE_* env, no banner.
10
+ export function buildBanner(env: HookEnv): BannerOutcome {
11
+ const repoPath = env.MATE_REPO_PATH;
12
+ const artifactPath = env.MATE_ARTIFACT_PATH;
13
+ if (!repoPath || !artifactPath) return { exitCode: 0, stdout: "" };
14
+
15
+ const mateVersion = env.MATE_VERSION || "unknown";
16
+ const message = `mate v${mateVersion}\n repo: ${repoPath}\n mate: ${artifactPath}`;
17
+ return { exitCode: 0, stdout: JSON.stringify({ systemMessage: message }) + "\n" };
18
+ }
19
+
20
+ // Plugin-shim entry.
21
+ export function run(): number {
22
+ const outcome = buildBanner(process.env);
23
+ if (outcome.stdout) process.stdout.write(outcome.stdout);
24
+ return outcome.exitCode;
25
+ }
@@ -0,0 +1,236 @@
1
+ // Block artifact writes outside the companion framework path.
2
+ //
3
+ // Artifact-like files may be written in the working repository only when the
4
+ // target path is already ignored by git. That keeps local-only scratch files
5
+ // possible without weakening the default repo split.
6
+ //
7
+ // Editing a file that already exists is always allowed: the guard exists to
8
+ // stop new agent artifacts from landing in the working repo, not to freeze
9
+ // files that are already part of it.
10
+ import { spawnSync } from "node:child_process";
11
+ import fs from "node:fs";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+
15
+ export type HookEnv = Record<string, string | undefined>;
16
+
17
+ export interface HookOutcome {
18
+ exitCode: number;
19
+ stderr: string;
20
+ }
21
+
22
+ const KNOWN_ARTIFACT_BASENAMES = new Set([
23
+ "CLAUDE.md",
24
+ "CONTEXT.md",
25
+ "design.md",
26
+ "explore-brief.md",
27
+ "proposal.md",
28
+ "spec.md",
29
+ "tasks.md",
30
+ ]);
31
+
32
+ const ARTIFACT_PATH_MARKERS = [
33
+ "/changes/",
34
+ "/openspec/",
35
+ "/specs/",
36
+ "/docs/adr/",
37
+ "/docs/adrs/",
38
+ "/docs/decisions/",
39
+ "/docs/prd/",
40
+ ];
41
+
42
+ const MD_REDIRECT_PATTERN = />{1,2}\s*([^\s;|&<>]+\.md)\b/g;
43
+ const MD_TEE_PATTERN = /\btee\s+(?:-a\s+)?([^\s;|&<>]+\.md)\b/g;
44
+
45
+ export function artifactLikePath(filePath: string): boolean {
46
+ if (!filePath) return false;
47
+
48
+ const basename = path.basename(filePath);
49
+ const normalized = "/" + filePath.replaceAll("\\", "/").replace(/^\/+/, "");
50
+ if (KNOWN_ARTIFACT_BASENAMES.has(basename)) return true;
51
+
52
+ if (ARTIFACT_PATH_MARKERS.some((marker) => normalized.includes(marker))) return true;
53
+
54
+ if (basename.endsWith(".md") && basename !== "README.md") return true;
55
+
56
+ return false;
57
+ }
58
+
59
+ function repoRoot(env: HookEnv): string {
60
+ return env.MATE_REPO_PATH || process.cwd();
61
+ }
62
+
63
+ function companionRoot(env: HookEnv): string | null {
64
+ const companion = env.MATE_ARTIFACT_PATH;
65
+ return companion ? path.normalize(companion) : null;
66
+ }
67
+
68
+ // Claude Code's own config/state directory (plan files, settings, todos).
69
+ // Writes there are agent-runtime state, never Mate artifacts.
70
+ function claudeConfigRoot(env: HookEnv): string {
71
+ const configured = env.CLAUDE_CONFIG_DIR;
72
+ if (configured) return path.normalize(configured);
73
+ return path.normalize(path.join(env.HOME || os.homedir(), ".claude"));
74
+ }
75
+
76
+ function normalizePath(filePath: string, env: HookEnv): string {
77
+ if (path.isAbsolute(filePath)) return path.normalize(filePath);
78
+ return path.normalize(path.join(repoRoot(env), filePath));
79
+ }
80
+
81
+ function isUnder(target: string, root: string): boolean {
82
+ const relative = path.relative(path.normalize(root), path.normalize(target));
83
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
84
+ }
85
+
86
+ function isGitignored(target: string, env: HookEnv): boolean {
87
+ const root = repoRoot(env);
88
+ if (!isUnder(target, root)) return false;
89
+
90
+ const relPath = path.relative(root, target);
91
+ const result = spawnSync("git", ["-C", root, "check-ignore", "--no-index", "-q", "--", relPath], {
92
+ stdio: "ignore",
93
+ });
94
+ return result.status === 0;
95
+ }
96
+
97
+ // A file already tracked in the working repo is product code being edited,
98
+ // not a new agent artifact (e.g. packaged SKILL.md/spec.md template sources).
99
+ function isGitTracked(target: string, env: HookEnv): boolean {
100
+ const root = repoRoot(env);
101
+ if (!isUnder(target, root)) return false;
102
+
103
+ const relPath = path.relative(root, target);
104
+ const result = spawnSync("git", ["-C", root, "ls-files", "--error-unmatch", "--", relPath], {
105
+ stdio: "ignore",
106
+ });
107
+ return result.status === 0;
108
+ }
109
+
110
+ function isProductDocumentationPath(target: string, env: HookEnv): boolean {
111
+ const root = repoRoot(env);
112
+ if (!isUnder(target, root)) return false;
113
+
114
+ const relPath = path.relative(root, target);
115
+ const parts = relPath.split(path.sep).filter(Boolean);
116
+ for (const [index, part] of parts.entries()) {
117
+ if (part === ".storybook" || part === "storybook") return true;
118
+
119
+ if (part !== "docs") continue;
120
+
121
+ const docsRoot = path.join(root, ...parts.slice(0, index + 1));
122
+ if (fs.existsSync(path.join(docsRoot, "package.json"))) return true;
123
+ }
124
+
125
+ return false;
126
+ }
127
+
128
+ function blockWrite(target: string, companion: string): HookOutcome {
129
+ const lines = [
130
+ "Mate guardrail: artifact writes must go to the companion framework path.",
131
+ ` target: ${target}`,
132
+ ` companion: ${companion}`,
133
+ "Use an absolute path under MATE_ARTIFACT_PATH instead.",
134
+ ];
135
+ if (path.basename(target) === "CLAUDE.md") {
136
+ lines.push(`Note: CLAUDE.md already lives in the companion repo at ${companion}/CLAUDE.md.`);
137
+ }
138
+ return { exitCode: 2, stderr: lines.join("\n") + "\n" };
139
+ }
140
+
141
+ function checkFilePath(
142
+ filePath: string,
143
+ companion: string | null,
144
+ env: HookEnv,
145
+ allowExisting = false,
146
+ ): HookOutcome | null {
147
+ if (!filePath || !companion) return null;
148
+
149
+ const normalized = normalizePath(filePath, env);
150
+ if (normalized.startsWith(companion)) return null;
151
+
152
+ if (isUnder(normalized, claudeConfigRoot(env))) return null;
153
+
154
+ if (allowExisting && fs.existsSync(normalized) && fs.statSync(normalized).isFile()) return null;
155
+
156
+ if (isProductDocumentationPath(normalized, env)) return null;
157
+
158
+ if (!artifactLikePath(filePath)) return null;
159
+
160
+ if (
161
+ isUnder(normalized, repoRoot(env)) &&
162
+ (isGitignored(normalized, env) || isGitTracked(normalized, env))
163
+ ) {
164
+ return null;
165
+ }
166
+
167
+ return blockWrite(filePath, companion);
168
+ }
169
+
170
+ export function commandMatches(command: string): string[] {
171
+ const targets: string[] = [];
172
+ for (const pattern of [MD_REDIRECT_PATTERN, MD_TEE_PATTERN]) {
173
+ const matcher = new RegExp(pattern.source, pattern.flags);
174
+ for (const match of command.matchAll(matcher)) {
175
+ const target = match[1].trim().replace(/^["']+|["']+$/g, "");
176
+ if (target) targets.push(target);
177
+ }
178
+ }
179
+ return targets;
180
+ }
181
+
182
+ export function evaluate(payload: unknown, env: HookEnv): HookOutcome {
183
+ const allow: HookOutcome = { exitCode: 0, stderr: "" };
184
+
185
+ const companion = companionRoot(env);
186
+ if (!companion) return allow;
187
+
188
+ const input = payload && typeof payload === "object" ? (payload as Record<string, unknown>) : {};
189
+ const toolName = typeof input.tool_name === "string" ? input.tool_name : "";
190
+ const toolInput =
191
+ input.tool_input && typeof input.tool_input === "object"
192
+ ? (input.tool_input as Record<string, unknown>)
193
+ : {};
194
+
195
+ if (toolName === "Write" || toolName === "Edit" || toolName === "MultiEdit") {
196
+ const outcome = checkFilePath(
197
+ String(toolInput.file_path ?? ""),
198
+ companion,
199
+ env,
200
+ toolName === "Edit" || toolName === "MultiEdit",
201
+ );
202
+ return outcome ?? allow;
203
+ }
204
+
205
+ if (toolName === "Bash") {
206
+ const command = String(toolInput.command ?? "");
207
+ for (const target of commandMatches(command)) {
208
+ const outcome = checkFilePath(target, companion, env);
209
+ if (outcome) return outcome;
210
+ }
211
+ return allow;
212
+ }
213
+
214
+ return allow;
215
+ }
216
+
217
+ async function readStdin(): Promise<string> {
218
+ const chunks: Buffer[] = [];
219
+ for await (const chunk of process.stdin) {
220
+ chunks.push(Buffer.from(chunk));
221
+ }
222
+ return Buffer.concat(chunks).toString("utf8");
223
+ }
224
+
225
+ // Plugin-shim entry: read the hook payload from stdin, evaluate, report.
226
+ export async function run(): Promise<number> {
227
+ let payload: unknown = {};
228
+ try {
229
+ payload = JSON.parse(await readStdin());
230
+ } catch {
231
+ payload = {};
232
+ }
233
+ const outcome = evaluate(payload, process.env);
234
+ if (outcome.stderr) process.stderr.write(outcome.stderr);
235
+ return outcome.exitCode;
236
+ }
package/src/index.ts CHANGED
@@ -47,7 +47,11 @@ export type {
47
47
  TemplatesService,
48
48
  } from "./tools/setup/plugin";
49
49
  export type {
50
+ FrameworkType,
50
51
  FrameworkConfig,
52
+ HubConfig,
53
+ HubMember,
54
+ HubMemberSource,
51
55
  PluginDeclaration,
52
56
  PluginDeclarationPolicy,
53
57
  } from "./lib/orchestrator/types";
@@ -20,7 +20,7 @@ export function isContextModePackageReference(value: unknown): value is string {
20
20
  }
21
21
 
22
22
  export function getContextModeInstallDir(companionPath: string): string {
23
- return path.join(companionPath, ".mate", "dependencies", CONTEXT_MODE_PACKAGE_NAME);
23
+ return path.join(companionPath, ".mate", "plugins", ".local");
24
24
  }
25
25
 
26
26
  export function getContextModePackageRoot(companionPath: string): string {
@@ -37,7 +37,9 @@ export function isContextModeNodeVersionSupported(version: string): boolean {
37
37
  }
38
38
 
39
39
  export function validateContextModeNodeRuntime(): void {
40
- const result = spawnSync("node", ["--version"], { encoding: "utf8" });
40
+ // env passed explicitly: bun's spawnSync otherwise ignores in-process PATH
41
+ // changes when resolving the executable.
42
+ const result = spawnSync("node", ["--version"], { encoding: "utf8", env: process.env });
41
43
  const version = result.stdout?.trim() ?? "";
42
44
  if (result.status !== 0 || !isContextModeNodeVersionSupported(version)) {
43
45
  throw new Error(
@@ -83,7 +85,7 @@ export async function installContextModePackage(companionPath: string): Promise<
83
85
  const result = spawnSync(
84
86
  "npm",
85
87
  ["install", "--no-audit", "--no-fund", "--silent", "--registry", PUBLIC_NPM_REGISTRY],
86
- { cwd: installDir, encoding: "utf8" },
88
+ { cwd: installDir, encoding: "utf8", env: process.env },
87
89
  );
88
90
  if (result.error || result.status !== 0) {
89
91
  throw new Error(