@workpowers/speckle 0.3.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -26,6 +26,34 @@ claude mcp add speckle -s user \
26
26
  Generate the key at **Account → MCP** (`/account#mcp`) on your Speckle host. One
27
27
  key covers every project you have access to.
28
28
 
29
+ ### Desktop and other GUI hosts
30
+
31
+ A desktop client starts the router from a fixed directory of its own — usually
32
+ your home directory — and its MCP client negotiates no `roots` capability, so
33
+ there is no way for it to tell the router where you are working. Name the
34
+ directory yourself:
35
+
36
+ ```json
37
+ {
38
+ "mcpServers": {
39
+ "speckle": {
40
+ "command": "npx",
41
+ "args": ["-y", "@workpowers/speckle"],
42
+ "env": {
43
+ "SPECKLE_MCP_BASE_URL": "https://speckle.workpowers.ai",
44
+ "SPECKLE_MCP_KEY": "lsk_your_key_here",
45
+ "SPECKLE_MCP_WORKSPACE_ROOT": "/Users/you/code/your-repo"
46
+ }
47
+ }
48
+ }
49
+ }
50
+ ```
51
+
52
+ Without it the session still works, but it runs rootless: discovery tools only,
53
+ and it cannot tell the server anything about your checkout — so freshness stays
54
+ `unknown` no matter what is installed on disk. `speckle-mcp doctor` prints which
55
+ directory it searched.
56
+
29
57
  ## Point a repo at a project
30
58
 
31
59
  Commit a `.speckle` marker at the repo root:
@@ -47,6 +75,30 @@ The router boots into one of two shapes depending on what it can see:
47
75
  as Claude Desktop). Discovery tools are registered instead, so the agent can
48
76
  find its way to a project first.
49
77
 
78
+ ## Keep workflow guidance current
79
+
80
+ The router observes dedicated local Speckle guidance on each tool call and
81
+ surfaces process revisions during an open session. Fetch `speckle_get_workflow`
82
+ before planning/resuming. The guide and the small repository bootstrap have
83
+ independent revisions; local file observations are attributed to the router,
84
+ never presented as independent server verification.
85
+
86
+ From a repository with a `.speckle` marker and the router environment configured:
87
+
88
+ ```sh
89
+ npx -y @workpowers/speckle workflow # preview only
90
+ npx -y @workpowers/speckle workflow --apply # dedicated bootstrap + local receipt
91
+ npx -y @workpowers/speckle workflow --apply --cache # also retain an offline planning cache
92
+ ```
93
+
94
+ Review the diff and reference `SPECKLE.md` from `AGENTS.md` or `CLAUDE.md`.
95
+ Reconcile old copied Speckle guidance while preserving project-specific rules.
96
+ Keep `.speckle-workflow.json` local (for example via Git's local exclude file).
97
+ The command refuses edited/unowned files and symlinks. No commits are made.
98
+ Unavailable live guidance is reported explicitly with any valid cache's revision
99
+ and age; a cache is never called current. Server releases carry new guidance;
100
+ restart the router after updating the router package itself.
101
+
50
102
  ## Diagnosing
51
103
 
52
104
  ```bash
@@ -63,9 +115,16 @@ which makes it the right first command when something feels off.
63
115
  |---|---|---|
64
116
  | `SPECKLE_MCP_KEY` | yes | Your API key. The only secret the router accepts. |
65
117
  | `SPECKLE_MCP_BASE_URL` | yes | The Speckle host. A marker's own `speckle_url` wins over it, so a repo can point at a different host than your default. |
118
+ | `SPECKLE_MCP_WORKSPACE_ROOT` | no | Directory to resolve the `.speckle` marker from, for hosts that cannot launch the router inside your repo. Takes priority over the process working directory. |
66
119
  | `SPECKLE_PROJECT_ID` | no | Fallback project binding for contexts with no marker. |
67
120
  | `SPECKLE_MCP_ALLOW_REPO_MISMATCH` | no | Set to `1` to proceed when the marker's repo does not match the checkout. |
68
121
 
122
+ `SPECKLE_MCP_WORKSPACE_ROOT` and `SPECKLE_PROJECT_ID` answer different
123
+ questions and do not substitute for each other. The project id says *which
124
+ project* a markerless session talks to; the workspace root says *which
125
+ directory on disk* to read. Only the second gives the router a checkout to
126
+ observe, so only the second lets it report whether your `SPECKLE.md` is current.
127
+
69
128
  A key is scoped to one Speckle host. If the marker selects a host your
70
129
  `SPECKLE_MCP_BASE_URL` disagrees with, the router refuses rather than sending
71
130
  your key somewhere it does not belong.
@@ -11,7 +11,7 @@ const args = process.argv.slice(2);
11
11
  const sub = args[0];
12
12
 
13
13
  const isCliSubcommand =
14
- sub === "init" || sub === "doctor" || sub === "help" || sub === "--help" || sub === "-h";
14
+ sub === "init" || sub === "doctor" || sub === "workflow" || sub === "help" || sub === "--help" || sub === "-h";
15
15
 
16
16
  if (isCliSubcommand) {
17
17
  runCli(args).catch((err) => {
package/dist/cli.js CHANGED
@@ -13,12 +13,15 @@
13
13
  import { writeFileSync, existsSync } from "node:fs";
14
14
  import path from "node:path";
15
15
  import { renderSpeckleMarker } from "./marker.js";
16
- import { resolveWorkspace } from "./workspace.js";
16
+ import { resolveWorkspace, workspaceOptionsFromConfig } from "./workspace.js";
17
17
  import { loadRouterConfig, resolveSpeckleHost } from "./config.js";
18
18
  import { SpeckleRouterError } from "./errors.js";
19
+ import { runWorkflowCommand } from "./workflow-command.js";
19
20
  export async function runCli(args) {
20
21
  const [cmd, ...rest] = args;
21
22
  switch (cmd) {
23
+ case "workflow":
24
+ return runWorkflowCommand(rest);
22
25
  case "init":
23
26
  return runInit(rest);
24
27
  case "doctor":
@@ -84,16 +87,22 @@ function runDoctor() {
84
87
  let config;
85
88
  try {
86
89
  config = loadRouterConfig();
87
- report.config = { baseUrl: config.baseUrl, keyConfigured: Boolean(config.apiKey) };
90
+ report.config = {
91
+ baseUrl: config.baseUrl,
92
+ keyConfigured: Boolean(config.apiKey),
93
+ // Named explicitly: when a marker is not found, the first question is
94
+ // always which directory was actually searched.
95
+ workspaceRoot: config.workspaceRoot ?? null,
96
+ workspaceRootSource: config.workspaceRoot ? "SPECKLE_MCP_WORKSPACE_ROOT" : "process cwd",
97
+ };
88
98
  }
89
99
  catch (err) {
90
100
  report.config = formatError(err);
91
101
  }
92
102
  try {
93
- const workspace = resolveWorkspace({
94
- cwd: process.cwd(),
95
- allowRepoMismatch: config?.allowRepoMismatch ?? false,
96
- });
103
+ const workspace = resolveWorkspace(config
104
+ ? workspaceOptionsFromConfig(config)
105
+ : { cwd: process.cwd(), allowRepoMismatch: false });
97
106
  report.workspace = {
98
107
  workspaceRoot: workspace.workspaceRoot,
99
108
  markerPath: workspace.markerPath,
@@ -138,6 +147,13 @@ function printHelp() {
138
147
  " --url <speckle_url> Optional Speckle host URL when not using the default.",
139
148
  " --force Overwrite an existing .speckle file.",
140
149
  " speckle-mcp doctor Diagnose local config and marker state (no network).",
150
+ "",
151
+ "Environment:",
152
+ " SPECKLE_MCP_WORKSPACE_ROOT Directory to resolve the .speckle marker from,",
153
+ " for hosts that launch the router outside the repo.",
154
+ " speckle-mcp workflow Fetch live guidance and preview dedicated local files.",
155
+ " --apply Apply after ownership checks; review the Git diff.",
156
+ " --cache Also keep planning guidance for explicit offline fallback.",
141
157
  " speckle-mcp help Show this message.",
142
158
  "",
143
159
  "Environment:",
package/dist/config.d.ts CHANGED
@@ -4,6 +4,13 @@
4
4
  * The router accepts only one secret (`SPECKLE_MCP_KEY`) and one optional
5
5
  * host hint (`SPECKLE_MCP_BASE_URL`). Everything else — project context,
6
6
  * repo identity — comes from the committed `.speckle` marker.
7
+ *
8
+ * `SPECKLE_MCP_WORKSPACE_ROOT` says WHERE to look for that marker when the
9
+ * process cannot be started inside the repo. A GUI host launches the router
10
+ * from a fixed directory, and its MCP client offers no `roots` capability to
11
+ * negotiate one, so the path has to arrive as launch configuration. It is a
12
+ * claim about where work happens, never proof of it: the marker still has to
13
+ * be there, and the repo cross-check still applies.
7
14
  */
8
15
  export interface RouterConfig {
9
16
  /** Speckle MCP base URL — `<host>/mcp` is constructed from this. */
@@ -12,8 +19,14 @@ export interface RouterConfig {
12
19
  apiKey: string;
13
20
  /** SPECKLE_MCP_ALLOW_REPO_MISMATCH=1 escape hatch state. */
14
21
  allowRepoMismatch: boolean;
15
- /** Process cwd at startup (workspace fallback when MCP roots are absent). */
22
+ /** Process cwd at startup — the fallback when no explicit root is configured. */
16
23
  cwd: string;
24
+ /**
25
+ * SPECKLE_MCP_WORKSPACE_ROOT — an explicit directory to resolve the marker
26
+ * from, for hosts that launch the router outside the repo. Takes priority
27
+ * over `cwd`; absent or blank, resolution behaves exactly as before.
28
+ */
29
+ workspaceRoot?: string;
17
30
  /**
18
31
  * SPECKLE_PROJECT_ID — optional fallback binding for markerless contexts
19
32
  * (Claude Desktop / Cowork, where the router process runs outside any
package/dist/config.js CHANGED
@@ -4,7 +4,15 @@
4
4
  * The router accepts only one secret (`SPECKLE_MCP_KEY`) and one optional
5
5
  * host hint (`SPECKLE_MCP_BASE_URL`). Everything else — project context,
6
6
  * repo identity — comes from the committed `.speckle` marker.
7
+ *
8
+ * `SPECKLE_MCP_WORKSPACE_ROOT` says WHERE to look for that marker when the
9
+ * process cannot be started inside the repo. A GUI host launches the router
10
+ * from a fixed directory, and its MCP client offers no `roots` capability to
11
+ * negotiate one, so the path has to arrive as launch configuration. It is a
12
+ * claim about where work happens, never proof of it: the marker still has to
13
+ * be there, and the repo cross-check still applies.
7
14
  */
15
+ import path from "node:path";
8
16
  import { SpeckleRouterError } from "./errors.js";
9
17
  export function loadRouterConfig(env = process.env) {
10
18
  const baseUrl = (env.SPECKLE_MCP_BASE_URL ?? "").trim();
@@ -22,9 +30,21 @@ export function loadRouterConfig(env = process.env) {
22
30
  apiKey,
23
31
  allowRepoMismatch: env.SPECKLE_MCP_ALLOW_REPO_MISMATCH === "1",
24
32
  cwd: process.cwd(),
33
+ workspaceRoot: parseWorkspaceRoot(env.SPECKLE_MCP_WORKSPACE_ROOT),
25
34
  fallbackProjectId: parseFallbackProjectId(env.SPECKLE_PROJECT_ID),
26
35
  };
27
36
  }
37
+ /**
38
+ * Parse the optional SPECKLE_MCP_WORKSPACE_ROOT. Blank counts as unset, the
39
+ * same way MCP bundle hosts pass empty strings for unfilled optional config.
40
+ * A path that does not exist is NOT rejected here: resolution already fails
41
+ * closed on a missing marker, and demoting to rootless is the safe outcome —
42
+ * failing the boot would take away the discovery tools as well.
43
+ */
44
+ function parseWorkspaceRoot(raw) {
45
+ const trimmed = (raw ?? "").trim();
46
+ return trimmed === "" ? undefined : path.resolve(trimmed);
47
+ }
28
48
  /**
29
49
  * Parse the optional SPECKLE_PROJECT_ID fallback. Empty/whitespace counts as
30
50
  * unset (MCP bundle hosts pass empty strings for blank optional config), but
package/dist/headers.d.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  */
14
14
  import type { ResolvedWorkspace } from "./workspace.js";
15
15
  export declare const ROUTER_CLIENT_NAME = "@workpowers/speckle";
16
- export declare const ROUTER_CLIENT_VERSION = "0.3.0";
16
+ export declare const ROUTER_CLIENT_VERSION = "0.5.0";
17
17
  export interface RouterRequestHeaders {
18
18
  Authorization: string;
19
19
  "X-Speckle-Client": string;
package/dist/headers.js CHANGED
@@ -12,7 +12,7 @@
12
12
  * the server then exposes a project-agnostic discovery toolset.
13
13
  */
14
14
  export const ROUTER_CLIENT_NAME = "@workpowers/speckle";
15
- export const ROUTER_CLIENT_VERSION = "0.3.0";
15
+ export const ROUTER_CLIENT_VERSION = "0.5.0";
16
16
  export function buildRouterHeaders(args) {
17
17
  const { apiKey, workspace, fallbackProjectId } = args;
18
18
  const headers = {
package/dist/index.d.ts CHANGED
@@ -7,7 +7,10 @@
7
7
  *
8
8
  * Flow:
9
9
  * 1. Load env config (`SPECKLE_MCP_BASE_URL`, `SPECKLE_MCP_KEY`).
10
- * 2. Resolve workspace + marker (cwd-based v1; MCP-roots support is a TODO).
10
+ * 2. Resolve workspace + marker from SPECKLE_MCP_WORKSPACE_ROOT when set,
11
+ * otherwise from process cwd. Protocol-level MCP roots are deliberately
12
+ * not the transport: the desktop client negotiates no `roots` capability,
13
+ * so a GUI host can only hand us a path as launch configuration.
11
14
  * If no marker is found, fall through to rootless mode (the server will
12
15
  * expose a project-agnostic discovery toolset instead). Other marker
13
16
  * errors (invalid TOML, remote mismatch, host mismatch) still fail loud
package/dist/index.js CHANGED
@@ -7,7 +7,10 @@
7
7
  *
8
8
  * Flow:
9
9
  * 1. Load env config (`SPECKLE_MCP_BASE_URL`, `SPECKLE_MCP_KEY`).
10
- * 2. Resolve workspace + marker (cwd-based v1; MCP-roots support is a TODO).
10
+ * 2. Resolve workspace + marker from SPECKLE_MCP_WORKSPACE_ROOT when set,
11
+ * otherwise from process cwd. Protocol-level MCP roots are deliberately
12
+ * not the transport: the desktop client negotiates no `roots` capability,
13
+ * so a GUI host can only hand us a path as launch configuration.
11
14
  * If no marker is found, fall through to rootless mode (the server will
12
15
  * expose a project-agnostic discovery toolset instead). Other marker
13
16
  * errors (invalid TOML, remote mismatch, host mismatch) still fail loud
@@ -27,18 +30,17 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
27
30
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
28
31
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
29
32
  import { loadRouterConfig, resolveSpeckleHost } from "./config.js";
30
- import { resolveWorkspace } from "./workspace.js";
33
+ import { resolveWorkspace, workspaceOptionsFromConfig, rootOriginFromConfig } from "./workspace.js";
31
34
  import { buildRouterHeaders, ROUTER_CLIENT_NAME, ROUTER_CLIENT_VERSION } from "./headers.js";
32
35
  import { mirrorServerOptions, wireProxyHandlers } from "./proxy.js";
33
36
  import { SpeckleRouterError } from "./errors.js";
37
+ import path from "node:path";
38
+ import { createWorkflowClient } from "./workflow-client.js";
34
39
  export async function startRouter() {
35
40
  const config = loadRouterConfig();
36
41
  let workspace;
37
42
  try {
38
- workspace = resolveWorkspace({
39
- cwd: config.cwd,
40
- allowRepoMismatch: config.allowRepoMismatch,
41
- });
43
+ workspace = resolveWorkspace(workspaceOptionsFromConfig(config));
42
44
  }
43
45
  catch (err) {
44
46
  if (err instanceof SpeckleRouterError && err.code === "marker_not_found") {
@@ -48,6 +50,9 @@ export async function startRouter() {
48
50
  }
49
51
  else {
50
52
  process.stderr.write("speckle-mcp: no .speckle marker found — running in rootless mode (discovery tools only). " +
53
+ (config.workspaceRoot
54
+ ? `Searched SPECKLE_MCP_WORKSPACE_ROOT (${config.workspaceRoot}) and upward. `
55
+ : "") +
51
56
  "Run `speckle-mcp init --project <id>` in a repo to bind it to a project.\n");
52
57
  }
53
58
  }
@@ -68,7 +73,12 @@ export async function startRouter() {
68
73
  await upstream.connect(httpTransport);
69
74
  const capabilities = upstream.getServerCapabilities() ?? {};
70
75
  const downstream = new Server({ name: ROUTER_CLIENT_NAME, version: ROUTER_CLIENT_VERSION }, mirrorServerOptions(upstream, capabilities));
71
- wireProxyHandlers(downstream, upstream, capabilities);
76
+ wireProxyHandlers(downstream, upstream, capabilities, createWorkflowClient({
77
+ root: workspace ? path.dirname(workspace.markerPath) : undefined,
78
+ workspaceId: workspace?.workspaceRootHash,
79
+ rootOrigin: rootOriginFromConfig(config),
80
+ host: host.hostUrl,
81
+ }));
72
82
  const stdio = new StdioServerTransport();
73
83
  await downstream.connect(stdio);
74
84
  // Forward shutdown so the upstream socket is closed when the agent disconnects.
package/dist/proxy.d.ts CHANGED
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
15
15
  import type { Server, ServerOptions } from "@modelcontextprotocol/sdk/server/index.js";
16
+ import type { createWorkflowClient } from "./workflow-client.js";
16
17
  import { type ServerCapabilities } from "@modelcontextprotocol/sdk/types.js";
17
18
  /**
18
19
  * The options the router's downstream Server must be built with to look like
@@ -32,5 +33,5 @@ import { type ServerCapabilities } from "@modelcontextprotocol/sdk/types.js";
32
33
  * passing `undefined` — the SDK stores what it is handed.
33
34
  */
34
35
  export declare function mirrorServerOptions(client: Client, capabilities: ServerCapabilities): ServerOptions;
35
- export declare function wireProxyHandlers(server: Server, client: Client, capabilities: ServerCapabilities): void;
36
+ export declare function wireProxyHandlers(server: Server, client: Client, capabilities: ServerCapabilities, workflow?: ReturnType<typeof createWorkflowClient>): void;
36
37
  //# sourceMappingURL=proxy.d.ts.map
package/dist/proxy.js CHANGED
@@ -33,7 +33,7 @@ export function mirrorServerOptions(client, capabilities) {
33
33
  const instructions = client.getInstructions();
34
34
  return { capabilities, ...(instructions === undefined ? {} : { instructions }) };
35
35
  }
36
- export function wireProxyHandlers(server, client, capabilities) {
36
+ export function wireProxyHandlers(server, client, capabilities, workflow) {
37
37
  // Ping is always available — agents use it to keep the link alive.
38
38
  server.setRequestHandler(PingRequestSchema, async () => {
39
39
  await client.ping();
@@ -44,7 +44,21 @@ export function wireProxyHandlers(server, client, capabilities) {
44
44
  return await client.listTools(req.params);
45
45
  });
46
46
  server.setRequestHandler(CallToolRequestSchema, async (req) => {
47
- return await client.callTool(req.params);
47
+ try {
48
+ const result = await client.callTool(workflow?.prepare(req.params) ?? req.params);
49
+ workflow?.received(req.params, result);
50
+ const fallback = result.isError ? workflow?.fallback(req.params) : undefined;
51
+ if (fallback && Array.isArray(result.content)) {
52
+ return { ...result, content: [...result.content, ...fallback.content] };
53
+ }
54
+ return result;
55
+ }
56
+ catch (error) {
57
+ const fallback = workflow?.fallback(req.params);
58
+ if (fallback)
59
+ return fallback;
60
+ throw error;
61
+ }
48
62
  });
49
63
  }
50
64
  if (capabilities.prompts !== undefined) {
@@ -0,0 +1,19 @@
1
+ import type { CallToolRequest } from "@modelcontextprotocol/sdk/types.js";
2
+ export declare function createWorkflowClient(options: {
3
+ root?: string;
4
+ workspaceId?: string;
5
+ host: string;
6
+ rootOrigin?: "config" | "cwd";
7
+ }): {
8
+ prepare(params: CallToolRequest["params"]): CallToolRequest["params"];
9
+ received(params: CallToolRequest["params"], result: unknown): void;
10
+ fallback(params: CallToolRequest["params"]): {
11
+ isError: boolean;
12
+ content: {
13
+ type: "text";
14
+ text: string;
15
+ }[];
16
+ } | undefined;
17
+ };
18
+ export declare function isWorkflowFetch(params: CallToolRequest["params"]): boolean;
19
+ //# sourceMappingURL=workflow-client.d.ts.map
@@ -0,0 +1,45 @@
1
+ /** Per-router-session metadata. Re-read checkout evidence on every call; never equate notice delivery with adoption. */
2
+ import { randomUUID } from "node:crypto";
3
+ import { z } from "zod";
4
+ import { WORKFLOW_META, publicationSchema } from "./workflow-contract.js";
5
+ import { observeWorkflowFiles, cachedWorkflowFallback } from "./workflow-files.js";
6
+ const responseMeta = z.object({
7
+ notice_id: z.string(), notice_delivered: z.boolean(), fetched_revision: z.string().optional(),
8
+ });
9
+ export function createWorkflowClient(options) {
10
+ const clientId = randomUUID();
11
+ let seenNotice;
12
+ let fetchedRevision;
13
+ return {
14
+ prepare(params) {
15
+ return { ...params, _meta: { ...params._meta, [WORKFLOW_META]: {
16
+ client_id: clientId, workspace_id: options.workspaceId ?? `rootless:${clientId}`,
17
+ seen_notice: seenNotice, fetched_revision: fetchedRevision,
18
+ ...(options.root
19
+ ? { evidence: observeWorkflowFiles(options.root, options.host, options.rootOrigin) }
20
+ : {}),
21
+ } } };
22
+ },
23
+ received(params, result) {
24
+ const r = result;
25
+ const meta = responseMeta.safeParse(r._meta?.[WORKFLOW_META]);
26
+ if (meta.success && meta.data.notice_delivered)
27
+ seenNotice = meta.data.notice_id;
28
+ // Only a successful explicit retrieval supplies session knowledge. Never an ordinary notice.
29
+ if (isWorkflowFetch(params) && !r.isError) {
30
+ const publication = publicationSchema.safeParse(r.structuredContent);
31
+ if (publication.success)
32
+ fetchedRevision = publication.data.planning.revision;
33
+ }
34
+ },
35
+ fallback(params) {
36
+ return isWorkflowFetch(params) ? { isError: true,
37
+ content: [{ type: "text", text: cachedWorkflowFallback(options.root, options.host) }] } : undefined;
38
+ },
39
+ };
40
+ }
41
+ export function isWorkflowFetch(params) {
42
+ return params.name === "speckle_get_workflow" || (params.name === "speckle_toolbox" &&
43
+ params.arguments?.tool === "speckle_get_workflow" && params.arguments.arguments !== undefined);
44
+ }
45
+ //# sourceMappingURL=workflow-client.js.map
@@ -0,0 +1,2 @@
1
+ export declare function runWorkflowCommand(args: string[]): Promise<void>;
2
+ //# sourceMappingURL=workflow-command.d.ts.map
@@ -0,0 +1,44 @@
1
+ /** Explicit workflow preview/apply command; reads only from the authenticated, configured Speckle host. */
2
+ import path from "node:path";
3
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
5
+ import { loadRouterConfig, resolveSpeckleHost } from "./config.js";
6
+ import { resolveWorkspace, workspaceOptionsFromConfig } from "./workspace.js";
7
+ import { buildRouterHeaders, ROUTER_CLIENT_NAME, ROUTER_CLIENT_VERSION } from "./headers.js";
8
+ import { publicationSchema } from "./workflow-contract.js";
9
+ import { applyWorkflowFiles, cachedWorkflowFallback } from "./workflow-files.js";
10
+ export async function runWorkflowCommand(args) {
11
+ if (args.some((arg) => arg !== "--apply" && arg !== "--cache")) {
12
+ throw new Error("Usage: speckle-mcp workflow [--apply] [--cache]");
13
+ }
14
+ const config = loadRouterConfig();
15
+ // Adoption has to work from wherever the host launches us: this is the
16
+ // command that installs the managed file, so a cwd-only resolution here
17
+ // would leave exactly the population this exists for unable to run it.
18
+ const workspace = resolveWorkspace(workspaceOptionsFromConfig(config));
19
+ const root = path.dirname(workspace.markerPath);
20
+ const host = resolveSpeckleHost(config, workspace.marker.marker.speckleUrl).hostUrl;
21
+ const client = new Client({ name: ROUTER_CLIENT_NAME, version: ROUTER_CLIENT_VERSION }, { capabilities: {} });
22
+ let publication;
23
+ try {
24
+ await client.connect(new StreamableHTTPClientTransport(new URL(`${host}/mcp`), {
25
+ requestInit: { headers: { ...buildRouterHeaders({ apiKey: config.apiKey, workspace }) } },
26
+ }));
27
+ const result = await client.callTool({ name: "speckle_get_workflow", arguments: { workflow: "planning" } }, undefined, { timeout: 15_000 });
28
+ if (result.isError)
29
+ throw new Error("Workflow tool refused retrieval");
30
+ publication = publicationSchema.parse(result.structuredContent);
31
+ }
32
+ catch {
33
+ process.stderr.write(cachedWorkflowFallback(root, host) + "\n");
34
+ throw new Error("Live workflow retrieval failed; no files were written. Retry against a server supporting speckle_get_workflow.");
35
+ }
36
+ finally {
37
+ await client.close().catch(() => undefined);
38
+ }
39
+ const result = applyWorkflowFiles(root, host, publication, {
40
+ apply: args.includes("--apply"), cache: args.includes("--cache"),
41
+ });
42
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
43
+ }
44
+ //# sourceMappingURL=workflow-command.js.map
@@ -0,0 +1,306 @@
1
+ import { z } from "zod";
2
+ export declare const WORKFLOW_META = "ai.workpowers.speckle/workflow";
3
+ export declare const BOOTSTRAP_FILE = "SPECKLE.md";
4
+ export declare const WORKFLOW_CACHE_FILE = ".speckle-workflow.json";
5
+ export declare const hashContent: (content: string) => string;
6
+ export declare const artifactSchema: z.ZodEffects<z.ZodObject<{
7
+ revision: z.ZodString;
8
+ content: z.ZodString;
9
+ summary: z.ZodString;
10
+ }, "strip", z.ZodTypeAny, {
11
+ revision: string;
12
+ content: string;
13
+ summary: string;
14
+ }, {
15
+ revision: string;
16
+ content: string;
17
+ summary: string;
18
+ }>, {
19
+ revision: string;
20
+ content: string;
21
+ summary: string;
22
+ }, {
23
+ revision: string;
24
+ content: string;
25
+ summary: string;
26
+ }>;
27
+ export declare const publicationSchema: z.ZodObject<{
28
+ protocol_version: z.ZodLiteral<1>;
29
+ planning: z.ZodEffects<z.ZodObject<{
30
+ revision: z.ZodString;
31
+ content: z.ZodString;
32
+ summary: z.ZodString;
33
+ }, "strip", z.ZodTypeAny, {
34
+ revision: string;
35
+ content: string;
36
+ summary: string;
37
+ }, {
38
+ revision: string;
39
+ content: string;
40
+ summary: string;
41
+ }>, {
42
+ revision: string;
43
+ content: string;
44
+ summary: string;
45
+ }, {
46
+ revision: string;
47
+ content: string;
48
+ summary: string;
49
+ }>;
50
+ bootstrap: z.ZodEffects<z.ZodObject<{
51
+ revision: z.ZodString;
52
+ content: z.ZodString;
53
+ summary: z.ZodString;
54
+ }, "strip", z.ZodTypeAny, {
55
+ revision: string;
56
+ content: string;
57
+ summary: string;
58
+ }, {
59
+ revision: string;
60
+ content: string;
61
+ summary: string;
62
+ }>, {
63
+ revision: string;
64
+ content: string;
65
+ summary: string;
66
+ }, {
67
+ revision: string;
68
+ content: string;
69
+ summary: string;
70
+ }>;
71
+ }, "strip", z.ZodTypeAny, {
72
+ protocol_version: 1;
73
+ planning: {
74
+ revision: string;
75
+ content: string;
76
+ summary: string;
77
+ };
78
+ bootstrap: {
79
+ revision: string;
80
+ content: string;
81
+ summary: string;
82
+ };
83
+ }, {
84
+ protocol_version: 1;
85
+ planning: {
86
+ revision: string;
87
+ content: string;
88
+ summary: string;
89
+ };
90
+ bootstrap: {
91
+ revision: string;
92
+ content: string;
93
+ summary: string;
94
+ };
95
+ }>;
96
+ export type WorkflowPublication = z.infer<typeof publicationSchema>;
97
+ declare const observation: z.ZodObject<{
98
+ state: z.ZodEnum<["observed", "missing", "unreadable"]>;
99
+ hash: z.ZodOptional<z.ZodString>;
100
+ baseline_hash: z.ZodOptional<z.ZodString>;
101
+ }, "strip", z.ZodTypeAny, {
102
+ state: "missing" | "observed" | "unreadable";
103
+ hash?: string | undefined;
104
+ baseline_hash?: string | undefined;
105
+ }, {
106
+ state: "missing" | "observed" | "unreadable";
107
+ hash?: string | undefined;
108
+ baseline_hash?: string | undefined;
109
+ }>;
110
+ export declare const workflowContextSchema: z.ZodObject<{
111
+ client_id: z.ZodOptional<z.ZodString>;
112
+ workspace_id: z.ZodOptional<z.ZodString>;
113
+ fetched_revision: z.ZodOptional<z.ZodString>;
114
+ seen_notice: z.ZodOptional<z.ZodString>;
115
+ evidence: z.ZodOptional<z.ZodObject<{
116
+ source: z.ZodEnum<["router", "agent"]>;
117
+ root_origin: z.ZodOptional<z.ZodEnum<["config", "cwd"]>>;
118
+ bootstrap: z.ZodObject<{
119
+ state: z.ZodEnum<["observed", "missing", "unreadable"]>;
120
+ hash: z.ZodOptional<z.ZodString>;
121
+ baseline_hash: z.ZodOptional<z.ZodString>;
122
+ }, "strip", z.ZodTypeAny, {
123
+ state: "missing" | "observed" | "unreadable";
124
+ hash?: string | undefined;
125
+ baseline_hash?: string | undefined;
126
+ }, {
127
+ state: "missing" | "observed" | "unreadable";
128
+ hash?: string | undefined;
129
+ baseline_hash?: string | undefined;
130
+ }>;
131
+ planning_cache: z.ZodOptional<z.ZodObject<{
132
+ state: z.ZodEnum<["observed", "missing", "unreadable"]>;
133
+ hash: z.ZodOptional<z.ZodString>;
134
+ baseline_hash: z.ZodOptional<z.ZodString>;
135
+ }, "strip", z.ZodTypeAny, {
136
+ state: "missing" | "observed" | "unreadable";
137
+ hash?: string | undefined;
138
+ baseline_hash?: string | undefined;
139
+ }, {
140
+ state: "missing" | "observed" | "unreadable";
141
+ hash?: string | undefined;
142
+ baseline_hash?: string | undefined;
143
+ }>>;
144
+ }, "strip", z.ZodTypeAny, {
145
+ bootstrap: {
146
+ state: "missing" | "observed" | "unreadable";
147
+ hash?: string | undefined;
148
+ baseline_hash?: string | undefined;
149
+ };
150
+ source: "router" | "agent";
151
+ root_origin?: "config" | "cwd" | undefined;
152
+ planning_cache?: {
153
+ state: "missing" | "observed" | "unreadable";
154
+ hash?: string | undefined;
155
+ baseline_hash?: string | undefined;
156
+ } | undefined;
157
+ }, {
158
+ bootstrap: {
159
+ state: "missing" | "observed" | "unreadable";
160
+ hash?: string | undefined;
161
+ baseline_hash?: string | undefined;
162
+ };
163
+ source: "router" | "agent";
164
+ root_origin?: "config" | "cwd" | undefined;
165
+ planning_cache?: {
166
+ state: "missing" | "observed" | "unreadable";
167
+ hash?: string | undefined;
168
+ baseline_hash?: string | undefined;
169
+ } | undefined;
170
+ }>>;
171
+ }, "strip", z.ZodTypeAny, {
172
+ client_id?: string | undefined;
173
+ workspace_id?: string | undefined;
174
+ fetched_revision?: string | undefined;
175
+ seen_notice?: string | undefined;
176
+ evidence?: {
177
+ bootstrap: {
178
+ state: "missing" | "observed" | "unreadable";
179
+ hash?: string | undefined;
180
+ baseline_hash?: string | undefined;
181
+ };
182
+ source: "router" | "agent";
183
+ root_origin?: "config" | "cwd" | undefined;
184
+ planning_cache?: {
185
+ state: "missing" | "observed" | "unreadable";
186
+ hash?: string | undefined;
187
+ baseline_hash?: string | undefined;
188
+ } | undefined;
189
+ } | undefined;
190
+ }, {
191
+ client_id?: string | undefined;
192
+ workspace_id?: string | undefined;
193
+ fetched_revision?: string | undefined;
194
+ seen_notice?: string | undefined;
195
+ evidence?: {
196
+ bootstrap: {
197
+ state: "missing" | "observed" | "unreadable";
198
+ hash?: string | undefined;
199
+ baseline_hash?: string | undefined;
200
+ };
201
+ source: "router" | "agent";
202
+ root_origin?: "config" | "cwd" | undefined;
203
+ planning_cache?: {
204
+ state: "missing" | "observed" | "unreadable";
205
+ hash?: string | undefined;
206
+ baseline_hash?: string | undefined;
207
+ } | undefined;
208
+ } | undefined;
209
+ }>;
210
+ export type WorkflowContext = z.infer<typeof workflowContextSchema>;
211
+ export type FileObservation = z.infer<typeof observation>;
212
+ export declare const cacheSchema: z.ZodObject<{
213
+ protocol_version: z.ZodLiteral<1>;
214
+ host: z.ZodString;
215
+ fetched_at: z.ZodString;
216
+ bootstrap: z.ZodEffects<z.ZodObject<{
217
+ revision: z.ZodString;
218
+ content: z.ZodString;
219
+ summary: z.ZodString;
220
+ }, "strip", z.ZodTypeAny, {
221
+ revision: string;
222
+ content: string;
223
+ summary: string;
224
+ }, {
225
+ revision: string;
226
+ content: string;
227
+ summary: string;
228
+ }>, {
229
+ revision: string;
230
+ content: string;
231
+ summary: string;
232
+ }, {
233
+ revision: string;
234
+ content: string;
235
+ summary: string;
236
+ }>;
237
+ planning: z.ZodOptional<z.ZodEffects<z.ZodObject<{
238
+ revision: z.ZodString;
239
+ content: z.ZodString;
240
+ summary: z.ZodString;
241
+ }, "strip", z.ZodTypeAny, {
242
+ revision: string;
243
+ content: string;
244
+ summary: string;
245
+ }, {
246
+ revision: string;
247
+ content: string;
248
+ summary: string;
249
+ }>, {
250
+ revision: string;
251
+ content: string;
252
+ summary: string;
253
+ }, {
254
+ revision: string;
255
+ content: string;
256
+ summary: string;
257
+ }>>;
258
+ }, "strip", z.ZodTypeAny, {
259
+ protocol_version: 1;
260
+ bootstrap: {
261
+ revision: string;
262
+ content: string;
263
+ summary: string;
264
+ };
265
+ host: string;
266
+ fetched_at: string;
267
+ planning?: {
268
+ revision: string;
269
+ content: string;
270
+ summary: string;
271
+ } | undefined;
272
+ }, {
273
+ protocol_version: 1;
274
+ bootstrap: {
275
+ revision: string;
276
+ content: string;
277
+ summary: string;
278
+ };
279
+ host: string;
280
+ fetched_at: string;
281
+ planning?: {
282
+ revision: string;
283
+ content: string;
284
+ summary: string;
285
+ } | undefined;
286
+ }>;
287
+ export type WorkflowCache = z.infer<typeof cacheSchema>;
288
+ /** Match only bytes actually reported for this checkout, never a revision marker alone. */
289
+ export declare function compareObservation(observed: FileObservation | undefined, revision: string): "missing" | "unknown" | "matches_published" | "unrecognized" | "outdated" | "modified";
290
+ export declare function workflowStatus(publication: WorkflowPublication, context?: WorkflowContext): {
291
+ notice_id: string;
292
+ notify: boolean;
293
+ protocol_version: 1;
294
+ planning_revision: string;
295
+ bootstrap_revision: string;
296
+ session: string;
297
+ checkout: {
298
+ workspace_id: string | null;
299
+ evidence_source: string;
300
+ server_verified: boolean;
301
+ bootstrap: string;
302
+ planning_cache: string;
303
+ };
304
+ };
305
+ export {};
306
+ //# sourceMappingURL=workflow-contract.d.ts.map
@@ -0,0 +1,90 @@
1
+ /** Shared, versioned wire contract for live guidance. Client evidence is never authentication. */
2
+ import { createHash } from "node:crypto";
3
+ import { z } from "zod";
4
+ export const WORKFLOW_META = "ai.workpowers.speckle/workflow";
5
+ export const BOOTSTRAP_FILE = "SPECKLE.md";
6
+ export const WORKFLOW_CACHE_FILE = ".speckle-workflow.json";
7
+ export const hashContent = (content) => `sha256:${createHash("sha256").update(content, "utf8").digest("hex")}`;
8
+ const hash = z.string().regex(/^sha256:[a-f0-9]{64}$/);
9
+ const identity = z.string().min(1).max(160);
10
+ export const artifactSchema = z.object({
11
+ revision: hash,
12
+ content: z.string().min(1).max(64_000),
13
+ summary: z.string().min(1).max(500),
14
+ }).refine((a) => hashContent(a.content) === a.revision, "Content does not match its revision");
15
+ export const publicationSchema = z.object({
16
+ protocol_version: z.literal(1),
17
+ planning: artifactSchema,
18
+ bootstrap: artifactSchema,
19
+ });
20
+ const observation = z.object({
21
+ state: z.enum(["observed", "missing", "unreadable"]),
22
+ hash: hash.optional(),
23
+ baseline_hash: hash.optional(),
24
+ });
25
+ export const workflowContextSchema = z.object({
26
+ client_id: identity.optional(),
27
+ workspace_id: identity.optional(),
28
+ fetched_revision: hash.optional(),
29
+ seen_notice: hash.optional(),
30
+ evidence: z.object({
31
+ source: z.enum(["router", "agent"]),
32
+ // WHERE the observed root came from. A configured root is a static launch
33
+ // value: it can name a checkout nobody is working in, and that reads
34
+ // identically to the right one unless the origin travels with the report.
35
+ // Carried for consumers that show coverage; `workflowStatus` ignores it,
36
+ // so reporting it changes no existing answer.
37
+ root_origin: z.enum(["config", "cwd"]).optional(),
38
+ bootstrap: observation,
39
+ planning_cache: observation.optional(),
40
+ }).optional(),
41
+ });
42
+ export const cacheSchema = z.object({
43
+ protocol_version: z.literal(1),
44
+ host: z.string().url(),
45
+ fetched_at: z.string().datetime(),
46
+ bootstrap: artifactSchema,
47
+ planning: artifactSchema.optional(),
48
+ });
49
+ /** Match only bytes actually reported for this checkout, never a revision marker alone. */
50
+ export function compareObservation(observed, revision) {
51
+ if (!observed || observed.state === "unreadable")
52
+ return "unknown";
53
+ if (observed.state === "missing")
54
+ return "missing";
55
+ if (!observed.hash)
56
+ return "unknown";
57
+ if (observed.hash === revision)
58
+ return "matches_published";
59
+ if (!observed.baseline_hash)
60
+ return "unrecognized";
61
+ return observed.hash === observed.baseline_hash ? "outdated" : "modified";
62
+ }
63
+ export function workflowStatus(publication, context = {}) {
64
+ // Evidence without checkout scope must not be applied to the current checkout.
65
+ const evidence = context.workspace_id ? context.evidence : undefined;
66
+ const status = {
67
+ protocol_version: 1,
68
+ planning_revision: publication.planning.revision,
69
+ bootstrap_revision: publication.bootstrap.revision,
70
+ session: context.fetched_revision === publication.planning.revision ? "fetched" :
71
+ context.fetched_revision ? "outdated" : "unknown",
72
+ checkout: {
73
+ workspace_id: context.workspace_id ?? null,
74
+ evidence_source: evidence?.source ?? "none",
75
+ server_verified: false,
76
+ bootstrap: compareObservation(evidence?.bootstrap, publication.bootstrap.revision),
77
+ planning_cache: compareObservation(evidence?.planning_cache, publication.planning.revision),
78
+ },
79
+ };
80
+ const noticeId = hashContent(JSON.stringify({ status, client_id: context.client_id ?? null }));
81
+ const needsNotice = status.session !== "fetched" || status.checkout.bootstrap !== "matches_published" ||
82
+ !["unknown", "missing", "matches_published"].includes(status.checkout.planning_cache);
83
+ return {
84
+ ...status,
85
+ notice_id: noticeId,
86
+ // Receipt means delivered, not read, applied or approved. No cross-client cache.
87
+ notify: needsNotice && !(context.client_id && context.workspace_id && context.seen_notice === noticeId),
88
+ };
89
+ }
90
+ //# sourceMappingURL=workflow-contract.js.map
@@ -0,0 +1,33 @@
1
+ import { type WorkflowCache, type WorkflowPublication } from "./workflow-contract.js";
2
+ /** Fixed filenames, regular files only. Do not follow an instruction/cache symlink. */
3
+ export declare function readManagedFile(file: string): string | undefined;
4
+ export declare function readWorkflowCache(root: string, host: string): WorkflowCache | undefined;
5
+ export declare function observeWorkflowFiles(root: string, host: string, rootOrigin?: "config" | "cwd"): {
6
+ bootstrap: {
7
+ state: "missing" | "observed" | "unreadable";
8
+ hash?: string | undefined;
9
+ baseline_hash?: string | undefined;
10
+ };
11
+ planning_cache: {
12
+ state: "missing" | "observed" | "unreadable";
13
+ hash?: string | undefined;
14
+ baseline_hash?: string | undefined;
15
+ };
16
+ root_origin?: "config" | "cwd" | undefined;
17
+ source: "router";
18
+ };
19
+ /** Refuse modified/unowned files before writing either artifact. Recheck before each rename. */
20
+ export declare function applyWorkflowFiles(root: string, host: string, input: WorkflowPublication, options?: {
21
+ apply?: boolean;
22
+ cache?: boolean;
23
+ replace?: (file: string, content: string, expected: string | undefined) => void;
24
+ }): {
25
+ applied: boolean;
26
+ files: {
27
+ path: string;
28
+ content: string;
29
+ }[];
30
+ next_step: string;
31
+ };
32
+ export declare function cachedWorkflowFallback(root: string | undefined, host: string): string;
33
+ //# sourceMappingURL=workflow-files.d.ts.map
@@ -0,0 +1,148 @@
1
+ /** Bounded local observations and explicit, conflict-preserving application of dedicated workflow files. */
2
+ import { constants, openSync, fstatSync, readSync, closeSync, lstatSync, writeFileSync, renameSync, unlinkSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { BOOTSTRAP_FILE, WORKFLOW_CACHE_FILE, hashContent, cacheSchema, publicationSchema } from "./workflow-contract.js";
6
+ const MAX_FILE_BYTES = 256_000;
7
+ /** Fixed filenames, regular files only. Do not follow an instruction/cache symlink. */
8
+ export function readManagedFile(file) {
9
+ let fd;
10
+ try {
11
+ fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
12
+ }
13
+ catch (error) {
14
+ if (error.code === "ENOENT")
15
+ return undefined;
16
+ throw error;
17
+ }
18
+ try {
19
+ const stat = fstatSync(fd);
20
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES)
21
+ throw new Error("Managed workflow file is not a bounded regular file");
22
+ // Bound the read as well as the initial stat in case a file grows concurrently.
23
+ const buffer = Buffer.alloc(MAX_FILE_BYTES + 1);
24
+ let size = 0;
25
+ while (size < buffer.length) {
26
+ const count = readSync(fd, buffer, size, buffer.length - size, null);
27
+ if (count === 0)
28
+ break;
29
+ size += count;
30
+ }
31
+ if (size > MAX_FILE_BYTES)
32
+ throw new Error("Managed workflow file grew beyond the size limit");
33
+ return buffer.toString("utf8", 0, size);
34
+ }
35
+ finally {
36
+ closeSync(fd);
37
+ }
38
+ }
39
+ export function readWorkflowCache(root, host) {
40
+ const raw = readManagedFile(path.join(root, WORKFLOW_CACHE_FILE));
41
+ if (raw === undefined)
42
+ return undefined;
43
+ const cache = cacheSchema.parse(JSON.parse(raw));
44
+ if (cache.host !== host)
45
+ throw new Error("Workflow receipt belongs to another Speckle host");
46
+ if (Date.parse(cache.fetched_at) > Date.now() + 60_000)
47
+ throw new Error("Workflow receipt has a future timestamp");
48
+ return cache;
49
+ }
50
+ export function observeWorkflowFiles(root, host, rootOrigin) {
51
+ let cache;
52
+ let cacheUnreadable = false;
53
+ try {
54
+ cache = readWorkflowCache(root, host);
55
+ }
56
+ catch {
57
+ cacheUnreadable = true;
58
+ }
59
+ let bootstrap;
60
+ try {
61
+ const content = readManagedFile(path.join(root, BOOTSTRAP_FILE));
62
+ bootstrap = content === undefined ? { state: "missing" } : {
63
+ state: "observed", hash: hashContent(content), baseline_hash: cache?.bootstrap.revision,
64
+ };
65
+ }
66
+ catch {
67
+ bootstrap = { state: "unreadable" };
68
+ }
69
+ const planning_cache = cacheUnreadable ? { state: "unreadable" } : cache?.planning ? {
70
+ state: "observed", hash: hashContent(cache.planning.content), baseline_hash: cache.planning.revision,
71
+ } : { state: "missing" };
72
+ return { source: "router", ...(rootOrigin ? { root_origin: rootOrigin } : {}),
73
+ bootstrap, planning_cache };
74
+ }
75
+ /** Refuse modified/unowned files before writing either artifact. Recheck before each rename. */
76
+ export function applyWorkflowFiles(root, host, input, options = {}) {
77
+ const publication = publicationSchema.parse(input);
78
+ const bootstrapPath = path.join(root, BOOTSTRAP_FILE);
79
+ const cachePath = path.join(root, WORKFLOW_CACHE_FILE);
80
+ const previousBootstrap = readManagedFile(bootstrapPath);
81
+ const previousReceipt = readManagedFile(cachePath);
82
+ const previousCache = readWorkflowCache(root, host);
83
+ if (previousBootstrap !== undefined && previousBootstrap !== publication.bootstrap.content &&
84
+ hashContent(previousBootstrap) !== previousCache?.bootstrap.revision) {
85
+ throw new Error("SPECKLE.md is edited or unowned. Reconcile it manually; no files were written.");
86
+ }
87
+ const receipt = {
88
+ protocol_version: 1, host, fetched_at: new Date().toISOString(), bootstrap: publication.bootstrap,
89
+ // Once opted into caching, refresh it on subsequent apply operations as well.
90
+ ...((options.cache || previousCache?.planning) ? { planning: publication.planning } : {}),
91
+ };
92
+ const files = [{ path: BOOTSTRAP_FILE, content: publication.bootstrap.content },
93
+ { path: WORKFLOW_CACHE_FILE, content: JSON.stringify(receipt, null, 2) + "\n" }];
94
+ if (options.apply) {
95
+ const replace = options.replace ?? replaceManagedFile;
96
+ replace(bootstrapPath, files[0].content, previousBootstrap);
97
+ if (readManagedFile(bootstrapPath) !== files[0].content)
98
+ throw new Error("Bootstrap verification failed; receipt not advanced");
99
+ // The receipt advances only after verifying the installed bootstrap bytes.
100
+ replace(cachePath, files[1].content, previousReceipt);
101
+ if (readManagedFile(cachePath) !== files[1].content || readManagedFile(bootstrapPath) !== files[0].content) {
102
+ throw new Error("Workflow application did not verify; re-read files before retrying");
103
+ }
104
+ }
105
+ return { applied: Boolean(options.apply), files,
106
+ next_step: "Review the diff. Add a reference to SPECKLE.md in AGENTS.md/CLAUDE.md after reconciling old Speckle guidance; preserve project conventions. Keep .speckle-workflow.json local (a receipt/optional cache), not a copied planning manual." };
107
+ }
108
+ function replaceManagedFile(file, content, expected) {
109
+ if (readManagedFile(file) !== expected)
110
+ throw new Error("Workflow file changed since preview; retry after reviewing it");
111
+ if (expected === content)
112
+ return;
113
+ const temp = `${file}.${randomUUID()}.tmp`;
114
+ try {
115
+ writeFileSync(temp, content, { flag: "wx", mode: 0o600 });
116
+ if (readManagedFile(file) !== expected)
117
+ throw new Error("Workflow file changed during update; preserved it");
118
+ // lstat refuses a dangling link (readManagedFile otherwise reports ENOENT).
119
+ try {
120
+ if (lstatSync(file).isSymbolicLink())
121
+ throw new Error("Refusing a workflow symlink");
122
+ }
123
+ catch (error) {
124
+ if (error.code !== "ENOENT")
125
+ throw error;
126
+ }
127
+ renameSync(temp, file);
128
+ }
129
+ finally {
130
+ try {
131
+ unlinkSync(temp);
132
+ }
133
+ catch { /* rename already consumed it */ }
134
+ }
135
+ }
136
+ export function cachedWorkflowFallback(root, host) {
137
+ try {
138
+ const cache = root ? readWorkflowCache(root, host) : undefined;
139
+ if (!cache?.planning)
140
+ return "Live Speckle guidance unavailable; no valid planning cache. Freshness unknown. Retry live retrieval; preserve existing gates.";
141
+ const age = Math.max(0, Math.floor((Date.now() - Date.parse(cache.fetched_at)) / 1000));
142
+ return `Live Speckle guidance unavailable. CACHED planning ${cache.planning.revision}, fetched ${cache.fetched_at} (${age}s ago). Current revision is UNKNOWN. Existing gates still apply.\n\n${cache.planning.content}`;
143
+ }
144
+ catch {
145
+ return "Live Speckle guidance unavailable; local receipt/cache is unreadable, corrupt or from another host. Freshness unknown; retry live retrieval.";
146
+ }
147
+ }
148
+ //# sourceMappingURL=workflow-files.js.map
@@ -31,6 +31,21 @@ export interface ResolveOptions {
31
31
  /** Allow remote-mismatch via env (default off). */
32
32
  allowRepoMismatch?: boolean;
33
33
  }
34
+ /**
35
+ * Build resolution inputs from router config. An explicitly configured root
36
+ * takes priority over process cwd; with none set, this is the old behaviour
37
+ * exactly. Every caller goes through here so the three entry points — the
38
+ * router, `doctor` and the workflow command — cannot drift apart again.
39
+ */
40
+ export declare function workspaceOptionsFromConfig(config: {
41
+ workspaceRoot?: string;
42
+ cwd: string;
43
+ allowRepoMismatch: boolean;
44
+ }): ResolveOptions;
45
+ /** Where a resolved root came from, travelling with the evidence it produces. */
46
+ export declare function rootOriginFromConfig(config: {
47
+ workspaceRoot?: string;
48
+ }): "config" | "cwd";
34
49
  export declare function resolveWorkspace(opts?: ResolveOptions): ResolvedWorkspace;
35
50
  /**
36
51
  * Canonical form: `host:org/repo` (lowercase host, no trailing `.git`,
package/dist/workspace.js CHANGED
@@ -14,6 +14,23 @@ import { execFileSync } from "node:child_process";
14
14
  import { SpeckleRouterError } from "./errors.js";
15
15
  import { parseSpeckleMarker } from "./marker.js";
16
16
  const MARKER_FILENAME = ".speckle";
17
+ /**
18
+ * Build resolution inputs from router config. An explicitly configured root
19
+ * takes priority over process cwd; with none set, this is the old behaviour
20
+ * exactly. Every caller goes through here so the three entry points — the
21
+ * router, `doctor` and the workflow command — cannot drift apart again.
22
+ */
23
+ export function workspaceOptionsFromConfig(config) {
24
+ return {
25
+ ...(config.workspaceRoot ? { workspaceRoots: [config.workspaceRoot] } : {}),
26
+ cwd: config.cwd,
27
+ allowRepoMismatch: config.allowRepoMismatch,
28
+ };
29
+ }
30
+ /** Where a resolved root came from, travelling with the evidence it produces. */
31
+ export function rootOriginFromConfig(config) {
32
+ return config.workspaceRoot ? "config" : "cwd";
33
+ }
17
34
  export function resolveWorkspace(opts = {}) {
18
35
  const roots = (opts.workspaceRoots ?? []).filter(Boolean);
19
36
  const cwd = opts.cwd ?? process.cwd();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workpowers/speckle",
3
- "version": "0.3.2",
3
+ "version": "0.5.0",
4
4
  "description": "Local MCP router for Speckle — resolves project context from a committed .speckle marker and forwards calls to the remote Speckle MCP endpoint.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -20,7 +20,8 @@
20
20
  "test": "vitest run"
21
21
  },
22
22
  "dependencies": {
23
- "@modelcontextprotocol/sdk": "^1.27.1"
23
+ "@modelcontextprotocol/sdk": "^1.27.1",
24
+ "zod": "^3.25.76"
24
25
  },
25
26
  "devDependencies": {
26
27
  "@types/node": "^22.10.5",