devsmind-mcp 4.2.0 → 4.3.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.
Files changed (47) hide show
  1. package/README.md +27 -2
  2. package/dist/cli/add-repo.d.ts +20 -0
  3. package/dist/cli/add-repo.js +171 -0
  4. package/dist/cli/add-repo.js.map +1 -0
  5. package/dist/cli/branch.d.ts +24 -0
  6. package/dist/cli/branch.js +148 -0
  7. package/dist/cli/branch.js.map +1 -0
  8. package/dist/cli/index.js +54 -2
  9. package/dist/cli/index.js.map +1 -1
  10. package/dist/cli/init.js +6 -28
  11. package/dist/cli/init.js.map +1 -1
  12. package/dist/cli/integrations/memory-topics.js +1 -1
  13. package/dist/cli/integrations/memory-topics.js.map +1 -1
  14. package/dist/cli/integrations/prompt.d.ts +9 -0
  15. package/dist/cli/integrations/prompt.js +21 -0
  16. package/dist/cli/integrations/prompt.js.map +1 -1
  17. package/dist/cli/integrations/registry.d.ts +22 -6
  18. package/dist/cli/integrations/registry.js +68 -7
  19. package/dist/cli/integrations/registry.js.map +1 -1
  20. package/dist/cli/integrations/skill.d.ts +16 -10
  21. package/dist/cli/integrations/skill.js +108 -22
  22. package/dist/cli/integrations/skill.js.map +1 -1
  23. package/dist/cli/llm-client.js +15 -7
  24. package/dist/cli/llm-client.js.map +1 -1
  25. package/dist/cli/rule.js +2 -2
  26. package/dist/cli/rule.js.map +1 -1
  27. package/dist/cli/runner.d.ts +8 -0
  28. package/dist/cli/runner.js +12 -5
  29. package/dist/cli/runner.js.map +1 -1
  30. package/dist/cli/sync.d.ts +16 -0
  31. package/dist/cli/sync.js +80 -0
  32. package/dist/cli/sync.js.map +1 -1
  33. package/dist/db/database.d.ts +11 -0
  34. package/dist/db/database.js +25 -0
  35. package/dist/db/database.js.map +1 -1
  36. package/dist/db/indexer.d.ts +1 -1
  37. package/dist/db/indexer.js +3 -3
  38. package/dist/db/indexer.js.map +1 -1
  39. package/dist/mcp/server.js +342 -33
  40. package/dist/mcp/server.js.map +1 -1
  41. package/dist/utils/config.d.ts +26 -0
  42. package/dist/utils/config.js +42 -0
  43. package/dist/utils/config.js.map +1 -1
  44. package/dist/utils/devsmind-branch.d.ts +55 -0
  45. package/dist/utils/devsmind-branch.js +244 -0
  46. package/dist/utils/devsmind-branch.js.map +1 -0
  47. package/package.json +1 -1
@@ -56,6 +56,7 @@ const fs = __importStar(require("fs"));
56
56
  const express_1 = __importDefault(require("express"));
57
57
  const database_1 = require("../db/database");
58
58
  const config_1 = require("../utils/config");
59
+ const devsmind_branch_1 = require("../utils/devsmind-branch");
59
60
  const visualizer_1 = require("./visualizer");
60
61
  const diff_1 = require("../utils/diff");
61
62
  const revert_1 = require("../db/revert");
@@ -89,23 +90,23 @@ exports.DEVSMIND_PORT = 4513;
89
90
  */
90
91
  /** MCP prompts/list name for the workflow-contract prompt below — see createMcpServer's prompts handlers. */
91
92
  exports.DEVSMIND_PROMPT_NAME = 'devsmind-workflow';
92
- exports.DEVSMIND_INSTRUCTIONS = `DevsMind is this team's persistent shared code memory — not a personal tool you reach for only when asked to search something. Every teammate's AI agent, in every session, reads from the SAME graph you are about to write to. There is no "your copy."
93
-
94
- If you skip recording a change, you are not skipping a formality. You are leaving the whole team's graph stale for every other AI agent that queries this code later — tomorrow, on a different task, in a different session. And the reasoning behind your change (why it was made, what ticket drove it, what was broken before, what you tried and rejected) exists ONLY in this conversation, right now. It is not in the diff. It is not in the commit message. If it isn't captured at commit_changes this turn, it is gone forever — no reindex, no log, no git blame can recover it later.
95
-
96
- Non-negotiable workflow:
97
- 1. Call start_session once, before your first WRITE of the conversation (edit_node/commit_changes and the other mutating tools). It mints a session_id that every write REQUIRES — it ties a request's edits together on the local Activity log and makes them revertable as a unit — and every response echoes it back so it stays in front of you, including after a context compaction. Read-only tools (search_nodes, get_node_code, list_nodes, and the other getters) do NOT need it: search and read freely from the very first call. Never invent a session_id yourself; if a write errors saying session_id is required, start_session was skipped — call it now, then retry. If you are resuming a conversation that already called start_session earlier (visible in the reloaded history), reuse that same session_id instead of starting a new one.
98
- 2. Before any filesystem search, grep, or file read: call search_nodes FIRST — it is now the one call for both "find this node" AND "find where X lives across files", so you should not need an external grep. Two inputs, pass either or both: a natural-language query (a real phrase — drives meaning-matching, so "authentication" finds a node described only as "sign-in") and/or pattern, a REAL regex used exactly as you'd give it to grep (e.g. "heartRed|onLikeTap|item\.liked" — nothing is re-escaped or split for you). Pattern-only is a precision mode: exact grep + code-body matches, no semantic blur. It returns two buckets: nodes (the indexed graph — the primary answer for "which function/class", with a true nodes_total before the top-20 cap) and files (a real grep of every repo, or just the path scope if given — the answer for things the graph does not index: CSS, JSON, config, .env, markup, wiring like "where is CORS configured" or "what mounts this middleware" — each sample line reports which function/class it falls inside, and files_total tells you honestly whether there's more than the page shown; pass a bigger offset for the next page). Triage by each node's confidence and relevance, NOT by which name looks right to you — confidence reflects how many independent layers corroborated the hit, which your own reading of a name cannot. Lockfiles and build artifacts are excluded by default, so what comes back is real source. If the response carries a compacted field, it was trimmed to fit and says exactly what was dropped — all counts stay exact, and compact:false gets you the untrimmed payload. It only returns real evidence — genuinely-absent things come back empty with a hint; if so, retry once with a different pattern/query before concluding it is not there. Only drop to a manual grep/read if search_nodes itself says truncated, or you need full file context after it points you at the file.
99
- 3. To read one function/class: call get_node_code instead of opening the file, and do not follow it with a file read for context — this is the ONE node-read call, not a lean summary. It already includes the file's imports, the node's own name/type/signature/description, up to 20 named callers AND callees per direction (with exact uses/used_by counts even when the lists are capped), and up to 40 other declarations from the same file (file_outline — this is how you tell "was this renamed?" or "what else lives here" without opening the file). Reach further in the SAME call instead of a second tool: graph_depth + graph_direction walks the transitive graph past the direct neighbors already included (add graph_code:true for a whole call flow's source in one round trip — if some nodes' code doesn't fit the budget they are named in graph.code_omitted_node_ids, so fetch exactly those rather than re-running blind), and history:"full" returns every revision with diffable edits, pageable with history_limit/history_offset. Every capped section is honest about it (*_truncated, *_hint) — a hint means more is reachable in this same call, not a dead end.
100
- 4. Before touching any function's signature: get_node_code already includes its direct callers by name (used_by_nodes) — for the FULL transitive blast radius, pass graph_direction:"in" with a graph_depth of 2-3 in that same call. Git shows you what changed; it never shows you what depends on it. Find out before you break something, not after.
101
- 5. Before refactoring: get_node_code already includes the last 3 changes' reasoning by default — for the full revision trail with diffable before/after edits, pass history:"full" in that same call. Git blame tells you who and when; it never tells you why. The actual decision context only exists here.
102
- 6. Write EVERY file with edit_node — .ts, .vue, .css, .json, .xml, .md, anything — and never your editor's own edit/write tools. It takes file_path + old_string + new_string exactly like an ordinary edit tool and never refuses a file type; to create a file that doesn't exist yet, pass old_string: "" and the whole file as new_string. Because it knows where your text landed, it works out which function/class you changed automatically: no node_id to look up, no code_snapshot to send back. It answers with every caller of what you changed. The graph only ever holds source code (functions/classes/logic) though — writes landing outside any function (markup, config, an import) get no graph node, normal and expected, not a failure — but the whole-file change is still staged for the local activity log, so commit_changes makes it revertable there like any other edit.
103
- 7. If a file already got edited WITHOUT going through edit_node — your own editor's edit/write tool got used by mistake, or you're catching up on work from before this session — call stage_change to recover it: same file_path/old_string/new_string/replace_all/description shape as edit_node, but it traces and stages the change without touching the file, since new_string is already sitting on disk. It fails clearly (new_string not found) if the edit never actually happened, so it can't silently record the wrong thing. Always prefer edit_node going forward; stage_change exists only to catch up after the fact, not as a second way to make an edit.
104
- 8. commit_changes REQUIRES a message AND a reasoning — the call fails without either. message is the user's request, verbatim, that led to this commit; it builds a local, private, never-pushed activity log (devsmind view → Activity) grouping your work by request and letting the user revert a request as a whole. Pass the exact same text again on a later commit that's still answering the same request — that merges them into one entry instead of splitting it. reasoning (what_changed/why/goal) is ONE object covering everything staged since the last commit — a commit is one logical change, so it gets one why, recorded against every node it touches, not one per edit_node/stage_change call.
105
- 9. commit_changes also REFUSES any batch containing a brand-NEW node with no description — a description is what makes that node findable later by a natural-language search_nodes query instead of only by its exact identifier. If edit_node or stage_change just created a node, call add_description with it (1-3 sentences of what it does and the domain concepts involved — never a restatement of the name) before commit_changes will accept it. Nothing staged is lost by the refusal; retry the same commit_changes call once it's described. Existing nodes are never gated by this — only ones new this commit.
106
- 10. commit_changes is NOT git and never touches it. It writes only into DevsMind's own local graph/database (.devmind/) and local activity log — it never runs git add, git commit, git push, or any other git command, and its "commit" is a completely different thing from a git commit despite the shared word. Calling it successfully is not a signal to now go run git yourself: never run git add/git commit/git push on your own initiative just because commit_changes succeeded, or because you finished a task. Your real git commit — staging and committing the actual code changes — is the developer's decision, made separately, only when they explicitly ask for it, exactly like any other git action.
107
- 11. A workflow is a named log of how ONE piece of functionality grew, across many sessions — read it to learn how the code got this way. start_session tells you if there is a recent one worth continuing; otherwise, when starting work that might belong to an existing multi-session feature, call workflow_list. If a description matches, ask the user before continuing it, then workflow_bind to attach THIS session. Binding is local to you: it never moves, pauses, or steals anyone else's workflow, and two sessions can work different ones at the same time.
108
- 12. Once bound, commit_changes logs a step for you automatically — you do NOT need workflow_add_step for ordinary code work. Call it for the thing a commit cannot express: a DECISION OR RESEARCH FINDING THAT CHANGED NO CODE ("evaluated X, rejected it because Y"), attaching the docs behind it via doc_paths. That is the one kind of knowledge nothing else keeps — git has the diff, history has the per-node reasoning, but neither records what was considered and rejected. If you did work while unbound, or on the wrong workflow, workflow_sync attaches it afterwards from your local activity log: it previews first and only writes when you pass confirm:true, so nothing has to be got right in the moment.
93
+ exports.DEVSMIND_INSTRUCTIONS = `DevsMind is this team's persistent shared code memory — not a personal tool you reach for only when asked to search something. Every teammate's AI agent, in every session, reads from the SAME graph you are about to write to. There is no "your copy."
94
+
95
+ If you skip recording a change, you are not skipping a formality. You are leaving the whole team's graph stale for every other AI agent that queries this code later — tomorrow, on a different task, in a different session. And the reasoning behind your change (why it was made, what ticket drove it, what was broken before, what you tried and rejected) exists ONLY in this conversation, right now. It is not in the diff. It is not in the commit message. If it isn't captured at commit_changes this turn, it is gone forever — no reindex, no log, no git blame can recover it later.
96
+
97
+ Non-negotiable workflow:
98
+ 1. Call start_session once, before your first WRITE of the conversation (edit_node/commit_changes and the other mutating tools). It mints a session_id that every write REQUIRES — it ties a request's edits together on the local Activity log and makes them revertable as a unit — and every response echoes it back so it stays in front of you, including after a context compaction. Read-only tools (search_nodes, get_node_code, list_nodes, and the other getters) do NOT need it: search and read freely from the very first call. Never invent a session_id yourself; if a write errors saying session_id is required, start_session was skipped — call it now, then retry. If you are resuming a conversation that already called start_session earlier (visible in the reloaded history), reuse that same session_id instead of starting a new one.
99
+ 2. Before any filesystem search, grep, or file read: call search_nodes FIRST — it is now the one call for both "find this node" AND "find where X lives across files", so you should not need an external grep. Two inputs, pass either or both: a natural-language query (a real phrase — drives meaning-matching, so "authentication" finds a node described only as "sign-in") and/or pattern, a REAL regex used exactly as you'd give it to grep (e.g. "heartRed|onLikeTap|item\.liked" — nothing is re-escaped or split for you). Pattern-only is a precision mode: exact grep + code-body matches, no semantic blur. It returns two buckets: nodes (the indexed graph — the primary answer for "which function/class", with a true nodes_total before the top-20 cap) and files (a real grep of every repo, or just the path scope if given — the answer for things the graph does not index: CSS, JSON, config, .env, markup, wiring like "where is CORS configured" or "what mounts this middleware" — each sample line reports which function/class it falls inside, and files_total tells you honestly whether there's more than the page shown; pass a bigger offset for the next page). Triage by each node's confidence and relevance, NOT by which name looks right to you — confidence reflects how many independent layers corroborated the hit, which your own reading of a name cannot. Lockfiles and build artifacts are excluded by default, so what comes back is real source. If the response carries a compacted field, it was trimmed to fit and says exactly what was dropped — all counts stay exact, and compact:false gets you the untrimmed payload. It only returns real evidence — genuinely-absent things come back empty with a hint; if so, retry once with a different pattern/query before concluding it is not there. Only drop to a manual grep/read if search_nodes itself says truncated, or you need full file context after it points you at the file.
100
+ 3. To read one function/class: call get_node_code instead of opening the file, and do not follow it with a file read for context — this is the ONE node-read call, not a lean summary. It already includes the file's imports, the node's own name/type/signature/description, up to 20 named callers AND callees per direction (with exact uses/used_by counts even when the lists are capped), and up to 40 other declarations from the same file (file_outline — this is how you tell "was this renamed?" or "what else lives here" without opening the file). Reach further in the SAME call instead of a second tool: graph_depth + graph_direction walks the transitive graph past the direct neighbors already included (add graph_code:true for a whole call flow's source in one round trip — if some nodes' code doesn't fit the budget they are named in graph.code_omitted_node_ids, so fetch exactly those rather than re-running blind), and history:"full" returns every revision with diffable edits, pageable with history_limit/history_offset. Every capped section is honest about it (*_truncated, *_hint) — a hint means more is reachable in this same call, not a dead end.
101
+ 4. Before touching any function's signature: get_node_code already includes its direct callers by name (used_by_nodes) — for the FULL transitive blast radius, pass graph_direction:"in" with a graph_depth of 2-3 in that same call. Git shows you what changed; it never shows you what depends on it. Find out before you break something, not after.
102
+ 5. Before refactoring: get_node_code already includes the last 3 changes' reasoning by default — for the full revision trail with diffable before/after edits, pass history:"full" in that same call. Git blame tells you who and when; it never tells you why. The actual decision context only exists here.
103
+ 6. Write EVERY file with edit_node — .ts, .vue, .css, .json, .xml, .md, anything — and never your editor's own edit/write tools. It takes file_path + old_string + new_string exactly like an ordinary edit tool and never refuses a file type; to create a file that doesn't exist yet, pass old_string: "" and the whole file as new_string. Because it knows where your text landed, it works out which function/class you changed automatically: no node_id to look up, no code_snapshot to send back. It answers with every caller of what you changed. The graph only ever holds source code (functions/classes/logic) though — writes landing outside any function (markup, config, an import) get no graph node, normal and expected, not a failure — but the whole-file change is still staged for the local activity log, so commit_changes makes it revertable there like any other edit.
104
+ 7. If a file already got edited WITHOUT going through edit_node — your own editor's edit/write tool got used by mistake, or you're catching up on work from before this session — call stage_change to recover it: same file_path/old_string/new_string/replace_all/description shape as edit_node, but it traces and stages the change without touching the file, since new_string is already sitting on disk. It fails clearly (new_string not found) if the edit never actually happened, so it can't silently record the wrong thing. Always prefer edit_node going forward; stage_change exists only to catch up after the fact, not as a second way to make an edit.
105
+ 8. commit_changes REQUIRES a message AND a reasoning — the call fails without either. message is the user's request, verbatim, that led to this commit; it builds a local, private, never-pushed activity log (devsmind view → Activity) grouping your work by request and letting the user revert a request as a whole. Pass the exact same text again on a later commit that's still answering the same request — that merges them into one entry instead of splitting it. reasoning (what_changed/why/goal) is ONE object covering everything staged since the last commit — a commit is one logical change, so it gets one why, recorded against every node it touches, not one per edit_node/stage_change call.
106
+ 9. commit_changes also REFUSES any batch containing a brand-NEW node with no description — a description is what makes that node findable later by a natural-language search_nodes query instead of only by its exact identifier. If edit_node or stage_change just created a node, call add_description with it (1-3 sentences of what it does and the domain concepts involved — never a restatement of the name) before commit_changes will accept it. Nothing staged is lost by the refusal; retry the same commit_changes call once it's described. Existing nodes are never gated by this — only ones new this commit.
107
+ 10. commit_changes is NOT git and never touches it. It writes only into DevsMind's own local graph/database (.devmind/) and local activity log — it never runs git add, git commit, git push, or any other git command, and its "commit" is a completely different thing from a git commit despite the shared word. Calling it successfully is not a signal to now go run git yourself: never run git add/git commit/git push on your own initiative just because commit_changes succeeded, or because you finished a task. Your real git commit — staging and committing the actual code changes — is the developer's decision, made separately, only when they explicitly ask for it, exactly like any other git action.
108
+ 11. A workflow is a named log of how ONE piece of functionality grew, across many sessions — read it to learn how the code got this way. start_session tells you if there is a recent one worth continuing; otherwise, when starting work that might belong to an existing multi-session feature, call workflow_list. If a description matches, ask the user before continuing it, then workflow_bind to attach THIS session. Binding is local to you: it never moves, pauses, or steals anyone else's workflow, and two sessions can work different ones at the same time.
109
+ 12. Once bound, commit_changes logs a step for you automatically — you do NOT need workflow_add_step for ordinary code work. Call it for the thing a commit cannot express: a DECISION OR RESEARCH FINDING THAT CHANGED NO CODE ("evaluated X, rejected it because Y"), attaching the docs behind it via doc_paths. That is the one kind of knowledge nothing else keeps — git has the diff, history has the per-node reasoning, but neither records what was considered and rejected. If you did work while unbound, or on the wrong workflow, workflow_sync attaches it afterwards from your local activity log: it previews first and only writes when you pass confirm:true, so nothing has to be got right in the moment.
109
110
  13. commit_changes also REQUIRES a feedback object (5 fields) — this is the only channel that improves DevsMind over time, so answer it for real, not as a formality. Before writing "none" on any field, actually check: did anything in THIS task take an extra tool call, a guess, a re-read, or a wrong turn? There almost always is something, even on an easy task — a specific one-line answer with evidence (file:line) is far more useful than a reflexive "none". "none" is correct only when you genuinely paid attention and nothing applies. Noticed something worth reporting but aren't committing right now (or don't want to wait until you are)? Call add_feedback directly — same 5 categories, but any one or more, nothing required, no commit needed. Passing evidence (file + snippet) on a graph_problem/edge_problem gets it verified fresh at call time and marked confirmed instead of suspected.`;
110
111
  // Shared node-type taxonomy description, reused by update_history and add_description.
111
112
  const NODE_TYPE_DESCRIPTION = 'The type of node. Be highly specific and framework-aware. Choose from the taxonomy below (or use a custom value if nothing fits).\n\n' +
@@ -163,6 +164,28 @@ function bindDevmindPath(devmindPath) {
163
164
  function getBoundDevmindPath() {
164
165
  return boundDevmindPath;
165
166
  }
167
+ /**
168
+ * For a SCOPED indexing session (a caller-provided `scratchpad` filename, e.g. `add_repo`'s
169
+ * dedicated one) Phase 1 must only scan the ONE repo that session is for — otherwise
170
+ * `index_continue` would silently pull in every other repo's files too. Phase 2 (edge
171
+ * resolution, inside `index_complete`) deliberately stays whole-graph even for a scoped
172
+ * session — a newly-added repo's outgoing references need the full node set to resolve
173
+ * against, and an existing repo may gain a new incoming reference INTO it, so narrowing that
174
+ * step would be a correctness regression, not an optimization.
175
+ *
176
+ * The DEFAULT (unscoped) scratchpad's `current_repo` is never used to scope anything here —
177
+ * it's set as an incidental side effect of normal Phase 1 processing (whichever repo the last
178
+ * extracted file happened to be in), not a deliberate scope. Only an explicitly-provided
179
+ * `scratchpadFile` opts into this filtering.
180
+ */
181
+ function scopedRepoFiles(devmindPath, scratchpadFile, pad) {
182
+ const { repos, total_files } = (0, scanner_1.scanRepoFiles)(devmindPath);
183
+ if (!scratchpadFile || !pad.current_repo) {
184
+ return { files: repos.flatMap(r => r.files), totalFiles: total_files };
185
+ }
186
+ const scoped = repos.filter(r => r.repo_name === pad.current_repo);
187
+ return { files: scoped.flatMap(r => r.files), totalFiles: scoped.reduce((sum, r) => sum + r.files.length, 0) };
188
+ }
166
189
  // Walk up from a start directory to find a brain folder (`.devsmind`, or a legacy `.devmind`)
167
190
  // containing config.json. Both names are tried at every level — see utils/config.ts.
168
191
  // Resolve devmind_path from args, falling back to auto-detect from cwd
@@ -254,6 +277,22 @@ const LIST_NODES_DEFAULT_LIMIT = 100;
254
277
  /** Max characters of reasoning copied onto a workflow step — a timeline of 200 steps has to stay
255
278
  * readable in one response, and the full text is always still on the history rows. */
256
279
  const STEP_REASONING_CAP = 2000;
280
+ /** `add_repo`'s dedicated scratchpad filename — separate from the default whole-workspace one so
281
+ * a scoped single-repo indexing session can never collide with (or be mistaken for) it. Passed as
282
+ * `scratchpad` to index_checkpoint/index_continue/index_complete to keep working with it. */
283
+ const ADD_REPO_MCP_SCRATCHPAD = 'add_repo_scratchpad.json';
284
+ /** Max characters PER doc in `workflow_add_step`'s `doc_content` — generous enough for a real spec
285
+ * doc, small enough that one call can't dump a multi-MB blob through the MCP transport. */
286
+ const DOC_CONTENT_CAP = 500_000;
287
+ /** Max number of `doc_content` entries per `workflow_add_step` call — a step records one decision,
288
+ * not a document dump. */
289
+ const DOC_CONTENT_MAX_COUNT = 10;
290
+ /** Max number of `doc_uploads` entries per `workflow_add_step` call — same reasoning as
291
+ * DOC_CONTENT_MAX_COUNT. */
292
+ const DOC_UPLOAD_MAX_COUNT = 10;
293
+ /** Max size PER file copied in via `doc_uploads` — generous for a spec doc or a diagram export,
294
+ * small enough that one call can't copy a huge archive into `.devmind/workflows/`. */
295
+ const DOC_UPLOAD_MAX_BYTES = 20 * 1024 * 1024;
257
296
  /**
258
297
  * The part of a commit's reasoning worth carrying onto a workflow step: WHY it was done, what it
259
298
  * was for, and what was decided.
@@ -311,6 +350,26 @@ function getDatabase(devmindPath) {
311
350
  }
312
351
  return dbCache.get(dbFile);
313
352
  }
353
+ /**
354
+ * Evicts (closing first, best-effort) the cached `DevMindDatabase` for `devmindPath` — the next
355
+ * `getDatabase` call constructs a fresh one. Needed after `add_repo` writes a new repo into
356
+ * `config.json`: `DevMindDatabase` snapshots `ProjectContext` once, in its constructor
357
+ * (`toRepoRelativePath` reads `this.context.config.repos`, set there and never refreshed), so a
358
+ * cached instance from an earlier tool call in the SAME session (e.g. `start_session`) would
359
+ * otherwise keep producing `../<repo>/...`-style ids for the just-added repo's nodes instead of
360
+ * `{<repo>}/...`, having never seen it in `config.repos`.
361
+ */
362
+ function invalidateDatabase(devmindPath) {
363
+ const dbFile = path.join(devmindPath, 'brain.db');
364
+ const existing = dbCache.get(dbFile);
365
+ if (existing) {
366
+ try {
367
+ existing.close();
368
+ }
369
+ catch { /* best-effort */ }
370
+ dbCache.delete(dbFile);
371
+ }
372
+ }
314
373
  /**
315
374
  * Closes every cached DB connection (best-effort) and clears the cache. Normally only reached via
316
375
  * the SIGINT/SIGTERM shutdown handlers below; exported so tests can release a fixture's cached
@@ -362,7 +421,10 @@ const SESSION_EXEMPT_READ_TOOLS = new Set([
362
421
  // are gone, so they no longer belong here. `workflow_list` is NOT exempt any more either: it
363
422
  // reports `bound_workflow_id`, which is a per-session fact — without a session_id it could only
364
423
  // ever answer null, which reads as "you are on nothing" rather than "I cannot tell".
365
- 'get_activity_log'
424
+ 'get_activity_log',
425
+ // Pulls committed brain state down from git — no session-scoped state involved. push_devsmind_branch
426
+ // is NOT exempt: it's a real write (commit + push), same bar as commit_changes/workflow_add_step.
427
+ 'pull_devsmind_branch'
366
428
  ]);
367
429
  /**
368
430
  * Creates and wires up a DevsMind MCP Server instance.
@@ -473,7 +535,8 @@ function createMcpServer() {
473
535
  inputSchema: {
474
536
  type: 'object',
475
537
  properties: {
476
- devmind_path: { type: 'string', description: 'Absolute path to the .devmind directory' }
538
+ devmind_path: { type: 'string', description: 'Absolute path to the .devmind directory' },
539
+ scratchpad: { type: 'string', description: 'Advanced: only pass this if add_repo told you to. Selects a scoped indexing session (e.g. the one add_repo started) instead of the default whole-workspace one.' }
477
540
  },
478
541
  required: ['devmind_path']
479
542
  }
@@ -484,7 +547,8 @@ function createMcpServer() {
484
547
  inputSchema: {
485
548
  type: 'object',
486
549
  properties: {
487
- devmind_path: { type: 'string', description: 'Absolute path to the .devmind directory' }
550
+ devmind_path: { type: 'string', description: 'Absolute path to the .devmind directory' },
551
+ scratchpad: { type: 'string', description: 'Advanced: only pass this if add_repo told you to. Selects a scoped indexing session (e.g. the one add_repo started) instead of the default whole-workspace one.' }
488
552
  },
489
553
  required: ['devmind_path']
490
554
  }
@@ -495,7 +559,21 @@ function createMcpServer() {
495
559
  inputSchema: {
496
560
  type: 'object',
497
561
  properties: {
498
- devmind_path: { type: 'string', description: 'Absolute path to the .devmind directory' }
562
+ devmind_path: { type: 'string', description: 'Absolute path to the .devmind directory' },
563
+ scratchpad: { type: 'string', description: 'Advanced: only pass this if add_repo told you to. Selects a scoped indexing session (e.g. the one add_repo started) instead of the default whole-workspace one.' }
564
+ },
565
+ required: ['devmind_path']
566
+ }
567
+ },
568
+ {
569
+ name: 'add_repo',
570
+ description: 'Standalone mode only: add ONE new repo to this brain and index just that repo — the graph-scoping equivalent of index_start, but scoped to a single repo instead of the whole workspace. Registers the repo in config.json/.env, then extracts its structure locally (no LLM) and hands back a first batch of nodes to describe, same as index_start. Continue with index_continue / index_complete exactly as you would for a normal index, but ALWAYS pass the same scratchpad value this call returns — omitting it targets the unrelated whole-workspace session instead. Resumable: if a previous add_repo call is still mid-index, call this again with NO name/path and it tells you which repo and scratchpad to continue with, rather than starting over. Refuses with a clear error in embedded mode (an embedded brain already covers exactly the one repo it lives inside).',
571
+ inputSchema: {
572
+ type: 'object',
573
+ properties: {
574
+ devmind_path: { type: 'string', description: 'Absolute path to the .devmind directory' },
575
+ name: { type: 'string', description: 'New repo name. Omit (along with path) to resume a previous add_repo call that has not finished indexing yet.' },
576
+ path: { type: 'string', description: 'Absolute local path to the repo on this machine. Required together with name on a fresh call.' }
499
577
  },
500
578
  required: ['devmind_path']
501
579
  }
@@ -977,7 +1055,7 @@ function createMcpServer() {
977
1055
  },
978
1056
  {
979
1057
  name: 'workflow_add_step',
980
- description: 'Record ONE step on a workflow, with the docs behind it, in the same call. You do NOT need this for ordinary code work — commit_changes already adds a step automatically whenever the session is bound. Call it for the thing a commit cannot express: A DECISION OR RESEARCH FINDING THAT CHANGED NO CODE (e.g. "evaluated Razorpay, no split settlements, going with Stripe"). That is the one kind of knowledge nothing else in DevsMind keeps — git has the diff and history has the per-node reasoning, but neither records what was considered and rejected. Attach the docs it came from via doc_paths.',
1058
+ description: 'Record ONE step on a workflow, with the docs behind it, in the same call. You do NOT need this for ordinary code work — commit_changes already adds a step automatically whenever the session is bound. Call it for the thing a commit cannot express: A DECISION OR RESEARCH FINDING THAT CHANGED NO CODE (e.g. "evaluated Razorpay, no split settlements, going with Stripe"). That is the one kind of knowledge nothing else in DevsMind keeps — git has the diff and history has the per-node reasoning, but neither records what was considered and rejected. Attach the docs it came from three ways: doc_paths (reference a file that already exists in a configured repo, no copy), doc_uploads (COPY an existing file on disk — any type, PDF/docx/image included — into DevsMind\'s own storage; use this for a doc outside any repo, or one you want to survive its source being deleted), or doc_content (paste text you have in hand but that isn\'t a file at all, or no longer is).',
981
1059
  inputSchema: {
982
1060
  type: 'object',
983
1061
  properties: {
@@ -986,7 +1064,24 @@ function createMcpServer() {
986
1064
  summary: { type: 'string', description: 'One line: what was decided or found' },
987
1065
  reasoning: { type: 'string', description: 'The why behind it — what was considered, what was rejected, and on what grounds. This is the part nobody can reconstruct later from the code that survived.' },
988
1066
  node_ids: { type: 'array', items: { type: 'string' }, description: 'Optional node ids this step relates to. Leave empty for a pure research/decision step.' },
989
- doc_paths: { type: 'array', items: { type: 'string' }, description: 'Optional paths to research/spec docs behind this step, relative to the repo. Stored as PATHS, never copies, so they stay current and are already shared with your team — a path outside the configured repos is rejected, since it would not exist for anyone else.' }
1067
+ doc_paths: { type: 'array', items: { type: 'string' }, description: 'Optional paths to research/spec docs behind this step, relative to the repo. Stored as PATHS, never copies, so they stay current and are already shared with your team — a path outside the configured repos is rejected, since it would not exist for anyone else.' },
1068
+ doc_content: {
1069
+ type: 'array',
1070
+ items: {
1071
+ type: 'object',
1072
+ properties: {
1073
+ name: { type: 'string', description: 'File name for this doc, e.g. "interest-caveat.md" — sanitized before use.' },
1074
+ content: { type: 'string', description: `The doc's full text (max ${DOC_CONTENT_CAP.toLocaleString()} chars).` }
1075
+ },
1076
+ required: ['name', 'content']
1077
+ },
1078
+ description: `Optional: up to ${DOC_CONTENT_MAX_COUNT} docs whose CONTENT (not just a path) should be copied into DevsMind's own storage under .devmind/workflows/. Use this instead of doc_paths when the doc has no on-repo home, or when it must keep existing after its source file is deleted. Content is stored on disk, not inlined into future responses — workflow_get_context returns each artifact's file_path, and you read it from there.`
1079
+ },
1080
+ doc_uploads: {
1081
+ type: 'array',
1082
+ items: { type: 'string' },
1083
+ description: `Optional: up to ${DOC_UPLOAD_MAX_COUNT} absolute paths to files (any type; max ${(DOC_UPLOAD_MAX_BYTES / (1024 * 1024)).toFixed(0)}MB each) to COPY into DevsMind's own storage under .devmind/workflows/ — the actual bytes, not just the path. Unlike doc_paths there's no configured-repo restriction, since the point is capturing a doc that may not live in one (or won't stay on disk at all). Use this — not doc_content — whenever the doc already exists as a file; it's simpler and works for binary files doc_content can't hold as text.`
1084
+ }
990
1085
  },
991
1086
  required: ['devmind_path', 'summary']
992
1087
  }
@@ -1032,6 +1127,29 @@ function createMcpServer() {
1032
1127
  },
1033
1128
  required: ['devmind_path']
1034
1129
  }
1130
+ },
1131
+ {
1132
+ name: 'push_devsmind_branch',
1133
+ description: `Commit graph/history/vectors/workflows onto the dedicated '${devsmind_branch_1.DEVSMIND_BRANCH}' branch and push it. UNLIKE commit_changes, this DOES run real git commands (commit + push) — but only ever on the '${devsmind_branch_1.DEVSMIND_BRANCH}' branch, via a throwaway worktree, so the developer's actual checked-out branch is never touched, moved, or committed to. This exists so a PR diff shows only real code changes, not the hundreds of graph/history files DevsMind itself writes. Only call this when the developer has asked you to push, not as a routine follow-up to commit_changes. Requires a commit message.`,
1134
+ inputSchema: {
1135
+ type: 'object',
1136
+ properties: {
1137
+ devmind_path: { type: 'string', description: 'Absolute path to the .devmind directory' },
1138
+ message: { type: 'string', description: `Commit message for this snapshot on the '${devsmind_branch_1.DEVSMIND_BRANCH}' branch.` }
1139
+ },
1140
+ required: ['devmind_path', 'message']
1141
+ }
1142
+ },
1143
+ {
1144
+ name: 'pull_devsmind_branch',
1145
+ description: `Read-only counterpart to push_devsmind_branch: copies graph/history/vectors/workflows down from the '${devsmind_branch_1.DEVSMIND_BRANCH}' branch (remote-tracking ref preferred when a remote exists) into .devsmind/ on disk and re-syncs brain.db. Useful after a teammate has pushed — a plain git pull on the code branch no longer brings this data in once it lives on '${devsmind_branch_1.DEVSMIND_BRANCH}' instead.`,
1146
+ inputSchema: {
1147
+ type: 'object',
1148
+ properties: {
1149
+ devmind_path: { type: 'string', description: 'Absolute path to the .devmind directory' }
1150
+ },
1151
+ required: ['devmind_path']
1152
+ }
1035
1153
  }
1036
1154
  ];
1037
1155
  // Every tool except start_session (the one tool that CREATES a session) requires
@@ -1428,7 +1546,8 @@ function createMcpServer() {
1428
1546
  }
1429
1547
  case 'index_checkpoint': {
1430
1548
  const devmindPath = resolveDevmindPath(args.devmind_path);
1431
- const pad = (0, indexer_1.readScratchpad)(devmindPath);
1549
+ const scratchpadFile = args.scratchpad ? String(args.scratchpad) : undefined;
1550
+ const pad = (0, indexer_1.readScratchpad)(devmindPath, scratchpadFile);
1432
1551
  if (!pad) {
1433
1552
  return {
1434
1553
  content: [{ type: 'text', text: JSON.stringify({ error: 'No indexing session found. Call index_start first.' }) }]
@@ -1455,7 +1574,8 @@ function createMcpServer() {
1455
1574
  case 'index_continue': {
1456
1575
  const devmindPath = resolveDevmindPath(args.devmind_path);
1457
1576
  const db = getDatabase(devmindPath);
1458
- const pad = (0, indexer_1.readScratchpad)(devmindPath);
1577
+ const scratchpadFile = args.scratchpad ? String(args.scratchpad) : undefined;
1578
+ const pad = (0, indexer_1.readScratchpad)(devmindPath, scratchpadFile);
1459
1579
  if (!pad) {
1460
1580
  return {
1461
1581
  content: [{ type: 'text', text: JSON.stringify({ error: 'No indexing session found. Call index_start first.' }) }]
@@ -1476,8 +1596,7 @@ function createMcpServer() {
1476
1596
  'NEVER write or execute external scripts to index files — the server already extracted the structure; you only describe.'
1477
1597
  ];
1478
1598
  if (pad.phase === 1) {
1479
- const { repos } = (0, scanner_1.scanRepoFiles)(devmindPath);
1480
- const allFiles = repos.flatMap(r => r.files);
1599
+ const { files: allFiles } = scopedRepoFiles(devmindPath, scratchpadFile, pad);
1481
1600
  const startIdx = pad.last_file_indexed ? allFiles.findIndex(f => f === pad.last_file_indexed) + 1 : 0;
1482
1601
  const remainingFiles = allFiles.slice(startIdx);
1483
1602
  if (remainingFiles.length > 0) {
@@ -1485,7 +1604,7 @@ function createMcpServer() {
1485
1604
  pad.files_done += batch.filesExtracted.length;
1486
1605
  pad.last_file_indexed = batch.cursor;
1487
1606
  pad.nodes_created += batch.nodesCreated;
1488
- (0, indexer_1.writeScratchpad)(devmindPath, pad);
1607
+ (0, indexer_1.writeScratchpad)(devmindPath, pad, scratchpadFile);
1489
1608
  return {
1490
1609
  content: [{
1491
1610
  type: 'text',
@@ -1500,7 +1619,7 @@ function createMcpServer() {
1500
1619
  };
1501
1620
  }
1502
1621
  pad.phase = 2;
1503
- (0, indexer_1.writeScratchpad)(devmindPath, pad);
1622
+ (0, indexer_1.writeScratchpad)(devmindPath, pad, scratchpadFile);
1504
1623
  }
1505
1624
  return {
1506
1625
  content: [{
@@ -1519,7 +1638,8 @@ function createMcpServer() {
1519
1638
  case 'index_complete': {
1520
1639
  const devmindPath = resolveDevmindPath(args.devmind_path);
1521
1640
  const db = getDatabase(devmindPath);
1522
- const pad = (0, indexer_1.readScratchpad)(devmindPath);
1641
+ const scratchpadFile = args.scratchpad ? String(args.scratchpad) : undefined;
1642
+ const pad = (0, indexer_1.readScratchpad)(devmindPath, scratchpadFile);
1523
1643
  if (!pad) {
1524
1644
  return {
1525
1645
  content: [{ type: 'text', text: JSON.stringify({ error: 'No indexing session found. Call index_start first.' }) }]
@@ -1530,7 +1650,11 @@ function createMcpServer() {
1530
1650
  content: [{ type: 'text', text: JSON.stringify({ status: 'complete', message: 'Indexing already completed.', scratchpad: pad }, null, 2) }]
1531
1651
  };
1532
1652
  }
1533
- const { total_files } = (0, scanner_1.scanRepoFiles)(devmindPath);
1653
+ // Phase 1 completeness is checked against the SAME scope index_continue used to fill
1654
+ // it — the whole workspace for the default session, just this repo's files for a
1655
+ // scoped one (a scoped scratchpad's files_total never covers every other repo, so
1656
+ // comparing it against the unscoped total would report "incomplete" forever).
1657
+ const { totalFiles: total_files } = scopedRepoFiles(devmindPath, scratchpadFile, pad);
1534
1658
  if (pad.phase === 1 && pad.files_done < total_files) {
1535
1659
  return {
1536
1660
  isError: true,
@@ -1557,7 +1681,7 @@ function createMcpServer() {
1557
1681
  }]
1558
1682
  };
1559
1683
  }
1560
- const finalPad = (0, indexer_1.completeScratchpad)(devmindPath);
1684
+ const finalPad = (0, indexer_1.completeScratchpad)(devmindPath, scratchpadFile);
1561
1685
  db.vacuum();
1562
1686
  const undescribedCount = db.getAllNodes().filter(n => !n.deprecated && !n.description).length;
1563
1687
  return {
@@ -1582,6 +1706,94 @@ function createMcpServer() {
1582
1706
  }]
1583
1707
  };
1584
1708
  }
1709
+ case 'add_repo': {
1710
+ const devmindPath = resolveDevmindPath(args.devmind_path);
1711
+ const ctx = (0, config_1.loadProjectContext)(devmindPath);
1712
+ if (!(0, config_1.isStandaloneMode)(ctx.config)) {
1713
+ return {
1714
+ isError: true,
1715
+ content: [{ type: 'text', text: JSON.stringify({ error: 'add_repo is only available in standalone mode — an embedded brain already covers exactly the one repo it lives inside.' }) }]
1716
+ };
1717
+ }
1718
+ const existingPad = (0, indexer_1.readScratchpad)(devmindPath, ADD_REPO_MCP_SCRATCHPAD);
1719
+ if (existingPad && existingPad.status === 'in_progress' && existingPad.current_repo) {
1720
+ return {
1721
+ content: [{
1722
+ type: 'text',
1723
+ text: JSON.stringify({
1724
+ status: 'resuming',
1725
+ message: `An add_repo session for "${existingPad.current_repo}" is already in progress. Do NOT call add_repo again for it — call index_continue (or index_checkpoint to see where it stands) with scratchpad: "${ADD_REPO_MCP_SCRATCHPAD}".`,
1726
+ repo_name: existingPad.current_repo,
1727
+ scratchpad: existingPad
1728
+ }, null, 2)
1729
+ }]
1730
+ };
1731
+ }
1732
+ const name = args.name ? String(args.name).trim() : '';
1733
+ const repoPath = args.path ? String(args.path).trim() : '';
1734
+ if (!name || !repoPath) {
1735
+ return {
1736
+ isError: true,
1737
+ content: [{ type: 'text', text: JSON.stringify({ error: 'add_repo: both name and path are required to add a new repo (omit both only to resume a previous in-progress add_repo call — none was found).' }) }]
1738
+ };
1739
+ }
1740
+ if (ctx.config.repos.some(r => r.name === name)) {
1741
+ return {
1742
+ isError: true,
1743
+ content: [{ type: 'text', text: JSON.stringify({ error: `add_repo: a repo named "${name}" already exists in this brain.` }) }]
1744
+ };
1745
+ }
1746
+ if (!fs.existsSync(repoPath) || !fs.statSync(repoPath).isDirectory()) {
1747
+ return {
1748
+ isError: true,
1749
+ content: [{ type: 'text', text: JSON.stringify({ error: `add_repo: path does not exist or is not a directory: ${repoPath}` }) }]
1750
+ };
1751
+ }
1752
+ const pathKey = `REPO_${name.toUpperCase().replace(/[^A-Z0-9]/g, '_')}`;
1753
+ const configPath = path.join(devmindPath, 'config.json');
1754
+ ctx.config.repos.push({ name, path_key: pathKey });
1755
+ fs.writeFileSync(configPath, JSON.stringify(ctx.config, null, 2) + '\n', 'utf-8');
1756
+ const envPath = path.join(devmindPath, '.env');
1757
+ const envLines = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf-8').split('\n').filter(l => l.trim()) : [];
1758
+ envLines.push(`${pathKey}=${repoPath}`);
1759
+ fs.writeFileSync(envPath, envLines.join('\n') + '\n', 'utf-8');
1760
+ // A DB instance already cached by an earlier call THIS session (e.g. start_session)
1761
+ // would still be working from the config.repos snapshot it took at construction time —
1762
+ // see invalidateDatabase's doc comment. Evict it so node ids for the new repo's files
1763
+ // resolve to `{name}/...`, not a fallback `../name/...` relative path.
1764
+ invalidateDatabase(devmindPath);
1765
+ // index_start's own pattern, scoped to just this one repo.
1766
+ const db = getDatabase(devmindPath);
1767
+ const { repos } = (0, scanner_1.scanRepoFiles)(devmindPath);
1768
+ const scopedRepo = repos.find(r => r.repo_name === name);
1769
+ const allFiles = scopedRepo ? scopedRepo.files : [];
1770
+ const pad = (0, indexer_1.createScratchpad)(devmindPath, allFiles.length, ADD_REPO_MCP_SCRATCHPAD);
1771
+ pad.current_repo = name; // scopedRepoFiles relies on this to keep index_continue/index_complete scoped to just this repo
1772
+ const batch = (0, index_build_1.extractFilesIntoGraph)(db, allFiles);
1773
+ pad.files_done = batch.filesExtracted.length;
1774
+ pad.last_file_indexed = batch.cursor;
1775
+ pad.nodes_created = batch.nodesCreated;
1776
+ (0, indexer_1.writeScratchpad)(devmindPath, pad, ADD_REPO_MCP_SCRATCHPAD);
1777
+ return {
1778
+ content: [{
1779
+ type: 'text',
1780
+ text: JSON.stringify({
1781
+ status: 'started',
1782
+ message: `Repo "${name}" added to config.json/.env. Indexing started (structure only, no LLM) — describe every node in batch.nodes with ONE add_description call, then call index_continue for the next batch.`,
1783
+ repo_name: name,
1784
+ scratchpad: pad,
1785
+ batch: { files: batch.filesExtracted, nodes: batch.nodes, file_imports: batch.fileImports },
1786
+ instructions: [
1787
+ `Every index_continue / index_checkpoint / index_complete call for this repo MUST include scratchpad: "${ADD_REPO_MCP_SCRATCHPAD}" — omitting it targets the unrelated whole-workspace session instead.`,
1788
+ 'Describe every node in `batch.nodes` with ONE add_description call.',
1789
+ 'Then call index_continue (with the scratchpad param) for the next batch. Repeat until it reports no files remain.',
1790
+ 'Once every node is described, call index_complete (with the scratchpad param).',
1791
+ 'NEVER write or execute external scripts to index files.'
1792
+ ]
1793
+ }, null, 2)
1794
+ }]
1795
+ };
1796
+ }
1585
1797
  case 'edit_node': {
1586
1798
  const devmindPath = resolveDevmindPath(args.devmind_path);
1587
1799
  const editDb = getDatabase(devmindPath);
@@ -2758,6 +2970,66 @@ function createMcpServer() {
2758
2970
  }
2759
2971
  docPaths.push(db.toRepoRelativePath(abs));
2760
2972
  }
2973
+ // `doc_content` is the copy-in counterpart to doc_paths: for text that has no on-repo
2974
+ // home (or won't stay there), store the bytes in DevsMind itself via the same
2975
+ // workflow_artifacts mechanism workflow_import uses, rather than a path that can dangle.
2976
+ const rawDocContent = Array.isArray(args.doc_content) ? args.doc_content : [];
2977
+ if (rawDocContent.length > DOC_CONTENT_MAX_COUNT) {
2978
+ return {
2979
+ isError: true,
2980
+ content: [{ type: 'text', text: JSON.stringify({ error: `doc_content accepts at most ${DOC_CONTENT_MAX_COUNT} docs per step, got ${rawDocContent.length}.` }) }]
2981
+ };
2982
+ }
2983
+ const docContent = [];
2984
+ for (const raw of rawDocContent) {
2985
+ if (!raw || typeof raw !== 'object' || typeof raw.name !== 'string' || typeof raw.content !== 'string') {
2986
+ return {
2987
+ isError: true,
2988
+ content: [{ type: 'text', text: JSON.stringify({ error: 'Each doc_content entry needs a string `name` and a string `content`.' }) }]
2989
+ };
2990
+ }
2991
+ if (raw.content.length > DOC_CONTENT_CAP) {
2992
+ return {
2993
+ isError: true,
2994
+ content: [{ type: 'text', text: JSON.stringify({ error: `doc_content entry "${raw.name}" is ${raw.content.length} chars, over the ${DOC_CONTENT_CAP} cap.` }) }]
2995
+ };
2996
+ }
2997
+ docContent.push({ name: raw.name, content: raw.content });
2998
+ }
2999
+ // `doc_uploads` copies an existing file's bytes in — binary-safe, and no configured-repo
3000
+ // restriction (that restriction exists for doc_paths because a rejected reference is
3001
+ // useless to teammates; a copy has no such dependency on where the source lives).
3002
+ const rawDocUploads = Array.isArray(args.doc_uploads) ? args.doc_uploads.map(String) : [];
3003
+ if (rawDocUploads.length > DOC_UPLOAD_MAX_COUNT) {
3004
+ return {
3005
+ isError: true,
3006
+ content: [{ type: 'text', text: JSON.stringify({ error: `doc_uploads accepts at most ${DOC_UPLOAD_MAX_COUNT} files per step, got ${rawDocUploads.length}.` }) }]
3007
+ };
3008
+ }
3009
+ const docUploads = [];
3010
+ for (const raw of rawDocUploads) {
3011
+ const abs = path.isAbsolute(raw) ? path.resolve(raw) : path.resolve(path.dirname(devmindPath), raw);
3012
+ if (!fs.existsSync(abs)) {
3013
+ return {
3014
+ isError: true,
3015
+ content: [{ type: 'text', text: JSON.stringify({ error: `doc_upload does not exist on disk: ${raw}` }) }]
3016
+ };
3017
+ }
3018
+ const stat = fs.statSync(abs);
3019
+ if (!stat.isFile()) {
3020
+ return {
3021
+ isError: true,
3022
+ content: [{ type: 'text', text: JSON.stringify({ error: `doc_upload is not a file: ${raw}` }) }]
3023
+ };
3024
+ }
3025
+ if (stat.size > DOC_UPLOAD_MAX_BYTES) {
3026
+ return {
3027
+ isError: true,
3028
+ content: [{ type: 'text', text: JSON.stringify({ error: `doc_upload "${raw}" is ${stat.size} bytes, over the ${DOC_UPLOAD_MAX_BYTES} cap.` }) }]
3029
+ };
3030
+ }
3031
+ docUploads.push(abs);
3032
+ }
2761
3033
  const step = db.addWorkflowStep(workflowId, {
2762
3034
  summary: requireStr(args, 'summary', 'workflow_add_step'),
2763
3035
  reasoning: args.reasoning ? String(args.reasoning).slice(0, STEP_REASONING_CAP) : undefined,
@@ -2765,7 +3037,18 @@ function createMcpServer() {
2765
3037
  docPaths: docPaths.length ? docPaths : undefined,
2766
3038
  sessionId
2767
3039
  });
2768
- return { content: [{ type: 'text', text: JSON.stringify({ status: 'added', step }, null, 2) }] };
3040
+ const artifacts = [
3041
+ ...docContent.map(doc => db.addWorkflowArtifact(workflowId, { stepId: step.id, type: 'step_doc', sourceName: doc.name, content: doc.content })),
3042
+ ...docUploads.map(sourcePath => db.addWorkflowArtifactFromFile(workflowId, { stepId: step.id, type: 'step_doc', sourcePath }))
3043
+ ];
3044
+ return {
3045
+ content: [{
3046
+ type: 'text',
3047
+ // Artifact CONTENT is deliberately not echoed back — same reasoning as
3048
+ // getWorkflowContext (database.ts): the file_path is enough, and content just went in.
3049
+ text: JSON.stringify({ status: 'added', step, artifacts: artifacts.length ? artifacts : undefined }, null, 2)
3050
+ }]
3051
+ };
2769
3052
  }
2770
3053
  case 'workflow_bind': {
2771
3054
  const devmindPath = resolveDevmindPath(args.devmind_path);
@@ -2980,6 +3263,32 @@ function createMcpServer() {
2980
3263
  const result = (0, workflow_import_1.importWorkflowDocs)(db, args.folder_path ? String(args.folder_path) : undefined, args.file_path ? String(args.file_path) : undefined);
2981
3264
  return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
2982
3265
  }
3266
+ case 'push_devsmind_branch': {
3267
+ const devmindPath = resolveDevmindPath(args.devmind_path);
3268
+ const message = requireStr(args, 'message', 'push_devsmind_branch');
3269
+ const result = (0, devsmind_branch_1.pushDevsmindBranch)(devmindPath, message);
3270
+ const status = !result.committed && !result.pushed
3271
+ ? 'nothing_to_push'
3272
+ : result.pushed
3273
+ ? (result.committed ? 'pushed' : 'pushed_prior_commit')
3274
+ : 'committed_local_only';
3275
+ return { content: [{ type: 'text', text: JSON.stringify({ status, ...result }, null, 2) }] };
3276
+ }
3277
+ case 'pull_devsmind_branch': {
3278
+ const devmindPath = resolveDevmindPath(args.devmind_path);
3279
+ const result = (0, devsmind_branch_1.pullDevsmindBranch)(devmindPath);
3280
+ if (!result.found) {
3281
+ return {
3282
+ content: [{
3283
+ type: 'text',
3284
+ text: JSON.stringify({ status: 'not_found', message: `No '${devsmind_branch_1.DEVSMIND_BRANCH}' branch found locally or on the remote yet — run push_devsmind_branch first.`, ...result }, null, 2)
3285
+ }]
3286
+ };
3287
+ }
3288
+ const db = getDatabase(devmindPath);
3289
+ db.syncFromDisk();
3290
+ return { content: [{ type: 'text', text: JSON.stringify({ status: 'pulled', ...result, counts: db.getCounts() }, null, 2) }] };
3291
+ }
2983
3292
  // NOTE: `workflow_pause` and `workflow_resume` are retained as thin aliases for
2984
3293
  // `workflow_bind`. Their old meaning — move a single global pointer, pausing whoever else
2985
3294
  // held it — no longer exists, and could not be reproduced without reintroducing the bug