borgmcp 1.0.36 → 1.0.38

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/dist/index.js CHANGED
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import{Server as K}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as z}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as X,ListToolsRequestSchema as Y,ListPromptsRequestSchema as G,GetPromptRequestSchema as J}from"@modelcontextprotocol/sdk/types.js";import{getCubeInfo as Z,getRoleInfo as j,getRoster as ee,readLog as te,appendLog as re,submitReport as oe,ackLogEntry as ie,regen as T,listCubes as ne,createCube as se,updateCube as O,deleteCube as ae,createRole as ce,updateRole as le,patchRoleSection as $,patchTaxonomyClass as N,deleteRole as de,reassignDrone as pe,evictDrone as ue,getCube as w,checkSubscriptionStatus as me,createBillingPortalSession as be,createSubscription as he,syncRoles as ge,applyTemplate as ye,whoami as fe,roleRationale as _e,getValidToken as we}from"./remote-client.js";import{startHealthBeatTick as ve}from"./health-beat.js";import{getTemplate as S,listTemplateNames as U,resolveCubeDirectiveForCreate as xe,resolveCubeDirectiveForApply as ke,resolveMessageTaxonomyForCreate as $e}from"./templates.js";import{activeCubeWithFreshRegenIdentity as P,getActiveCube as y,setActiveCube as A,inboxPathForDrone as q}from"./cubes.js";import{addSessionStartHook as Se,addUserPromptSubmitHook as Ue}from"./config-utils.js";import{humanAgo as L,formatLogEntryMarkdown as qe,formatRegenMarkdown as M,getDronePlaybook as Ie,nullTaxonomyTip as Ee,regenWakePathDroneLabel as Ce}from"./regen-format.js";import{startLogStream as Re,getStreamStatus as I}from"./log-stream.js";import{renderRoleList as De}from"./list-roles-render.js";import{filterToolsForRole as je}from"./tool-scope.js";import{getPackageVersion as v,getOnDiskVersion as Te,handleVersionFlag as Oe}from"./version.js";import{renderStreamStatus as Ne,checkInboxMonitorHealthy as E,formatWakePathPrefix as Pe,shouldShowWakePathWarning as Ae}from"./stream-status.js";import{formatRoleAgentLabel as Le,renderRoster as Me}from"./roster-render.js";import{resolveDroneIdByLabel as Be,isUuidShape as Fe}from"./evict-drone.js";import{authRecoveryMessage as We}from"./auth-recovery.js";import{DroneEvictedError as He,DroneFrozenError as Qe,formatEvictedToolResult as Ve,formatFrozenToolResult as Ke}from"./drone-lifecycle.js";import{classifyInSessionAssimilate as ze,reattachOnlyRefusal as Xe,reattachFailureMessage as Ye}from"./assimilate-guard.js";import{gateAllowsActivation as Ge,borgSessionToolNotice as Je}from"./launch-gate.js";import{renderSyncRolesResult as Ze}from"./sync-roles-render.js";import{initConsolePrefix as et,consolePrefix as x}from"./console-prefix.js";import{isCodexRemoteWakeEnabled as C,resolveSessionAgentKind as tt,probeCodexBridgeArmed as rt}from"./codex-app-wake.js";import{lifecycleSignalForMessage as ot,recordLifecycleLog as B,shouldSuppressLifecycleLog as it}from"./lifecycle-log-guard.js";import{normalizeDirectLogRecipients as nt}from"./direct-log.js";import F from"open";import st from"os";function at(){try{const p=st.hostname();return p&&p.trim()?p.trim().slice(0,255):null}catch{return null}}async function W(p,_){return await ye(p,_.name)}async function f(){const p=await y();if(!p)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");return p}async function ct(){Oe();try{Se()}catch{}try{Ue()}catch{}try{Re()}catch{}try{ve({getActiveCube:y,getStreamConnected:()=>I().connected,getInboxPath:u=>q(u.cubeId,u.droneId),checkMonitor:E,isCodexRemoteWake:C,probeBridgeArmed:u=>rt({cubeId:u.cubeId,droneId:u.droneId}),resolveAgentKind:tt,resolveHostname:at,resolveVersion:v,getToken:we,fetchImpl:globalThis.fetch.bind(globalThis)})}catch{}const p=new K({name:"borg-mcp-client",version:v()},{capabilities:{tools:{},prompts:{}}}),_=[{name:"borg_subscribe",description:"Create Stripe checkout session for Cube tier ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr). Free tier is permanent (1 cube + 3 agent sessions + 100 req/hr); no trial.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_upgrade-subscription",description:"Open the Stripe Billing Portal to manage Cube tier quantity ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr).",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_subscription_status",description:"Check subscription status",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_open_dashboard",description:"Open Borg MCP dashboard in browser to manage cubes, roles, and drones",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_regen",description:"Refresh your context as a Drone. Returns the active cube's directive, your role's detailed playbook, the drone roster, and recent activity log entries \u2014 everything you need to be oriented. Call on session start, and again before each new task to stay in sync with the cube. Returns \"not connected\" if no active cube; use borg_assimilate first in that case. Optional `since` (entry-id UUID or ISO-8601 timestamp) trims the recent-log section to entries strictly after the anchor \u2014 pass your last-seen entry id to skip already-processed history on each refresh.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional cursor. Either an activity_log entry id (UUID; server resolves to (created_at, id) tuple) OR an ISO-8601 timestamp. When provided, the recent-log section returns entries strictly after that anchor. Non-existent UUID falls back to default recent window."},mode:{type:"string",enum:["full","lite"],description:"Optional output mode. Use full at session start and after context compaction. Lite omits unchanged role playbook/directive/boilerplate while always showing dynamic safety information and recent activity."}},required:[]}},{name:"borg_assimilate",description:"RE-ATTACH this session to the drone seat already saved for this worktree (gh#780: this tool never creates seats). Provide the cube's name; on a match it returns the cube directive, your role's instructions, and recent activity for the EXISTING seat. To create a seat or switch cubes, run `borg assimilate` in a terminal instead.",inputSchema:{type:"object",properties:{cube_name:{type:"string",description:"The cube to connect to"}},required:["cube_name"]}},{name:"borg_cube",description:"Read the active Cube's directive and the registry of all roles in it (each role's name + short description). Use to remind yourself of cube-wide context.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_role",description:"Read your assigned role's detailed description (your playbook). Other drones cannot see this \u2014 only you (drones in this role).",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_version",description:"Returns the installed borgmcp client version. Use to verify which version is running in this MCP session.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_whoami",description:"Returns your identity in the current cube: cube name, drone label, and role name. Use to confirm which cube/role/drone you are.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_role-rationale",description:"Fetch an on-demand rationale/case-study section for a role playbook. Pass a role name/id and a plain-label section key to read the rationale without expanding every regen.",inputSchema:{type:"object",properties:{role:{type:"string",description:"Role name or role id to fetch rationale for, e.g. Builder."},section:{type:"string",description:"Plain-label role section key, e.g. Workflow rationale."}},required:["role","section"]}},{name:"borg_roster",description:"List all currently connected drones in your cube, with each drone's label, role, and last-seen time. Optional `since` argument adds a sender-side liveness column \u2014 pass either an activity_log entry id (e.g., from a dispatch you posted) or an ISO-8601 timestamp; each drone is marked `awake` if they've posted a log entry after that point, otherwise `stale-since-X`. Useful for confirming a dispatch reached its named recipients (catches the silent-wake-path-failure class where SSE delivered but the drone's /loop never woke).",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional liveness reference point. Either an activity_log entry id (UUID; server resolves to its created_at) OR an ISO-8601 timestamp. When provided, each drone in the output is tagged awake/stale relative to that point."}},required:[]}},{name:"borg_stream-status",description:"Diagnostic probe of the local SSE log-stream consumer: returns `connected`, `lastContentEventAt`, `lastWireActivityAt`, `lastHeartbeatAt`, `lastPersistedEventId`, `reconnectAttempts`, plus a wake-path check that flags if SSE is attached but no inbox-Monitor is watching the file (the silent failure where `/loop` never wakes on incoming entries). Read-only in-process state; does NOT re-open the stream. Use when troubleshooting wake-ups or verifying the stream is alive.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_read-log",description:"Read entries from the cube's activity log. Each entry is tagged with the drone that wrote it and that drone's role. For wake triage, prefer `unread_only=true` with a modest limit and drain until `has_more=false`; this reads oldest-unread-first from your server cursor and advances the watermark so bursts are not skipped. Optional `since` is a strict-after cursor for explicit bounded reads only; do not use it with the same timestamp as a notification preview because it can skip the boundary entry.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional strict-after cursor for explicit bounded reads. Either an activity_log entry id (UUID; server resolves to (created_at, id) tuple for deterministic tie-break) OR an ISO-8601 timestamp. Do not use for routine wake triage; prefer unread_only."},limit:{type:"number",description:"max entries to return (1-500)"},unread_only:{type:"boolean",description:"When true, read only entries posted after this drone last called read-log, oldest-unread-first. Server advances the watermark to the newest returned entry on every call; if has_more=true, call again until has_more=false."}}}},{name:"borg_ack",description:"Mark a log entry as explicitly acknowledged. Replaces the convention of posting `ACK: <dispatch-id>` log entries. The ack is recorded in a queryable DB flag (activity_log_acks) keyed on (entry_id, drone_id, kind). Idempotent \u2014 repeated calls on the same entry are no-ops. Use this whenever a previous workflow would have prompted you to log an ACK; it removes the noise from the cube log while keeping the signal queryable.",inputSchema:{type:"object",required:["entry_id"],properties:{entry_id:{type:"string",description:"UUID of the log entry to acknowledge."}}}},{name:"borg_log",description:"Append a message to the cube's activity log. By default entries broadcast to all drones. When a cube declares a message taxonomy, borg_log applies class-based smart defaults: prefix-matched directed classes route to their default recipients unless you pass `to:`, `class:`, or explicit visibility. Pass `to: [...]` to direct by exact drone label, drone id, role name, or role slug.",inputSchema:{type:"object",properties:{message:{type:"string",description:"The log message (max 10KB)."},to:{type:"array",items:{type:"string"},description:"Optional direct-message recipients by exact drone label, drone id, role name, or role slug (resolves to all drones in that role). Omit to let class-based routing or broadcast defaults apply."},class:{type:"string",description:"Optional declared message class. Overrides prefix auto-classification when the cube declares a message taxonomy."},visibility:{type:"string",enum:["broadcast","direct"],description:"Optional explicit visibility. Overrides class-based routing defaults."}},required:["message"]}},{name:"borg_report-friction",description:"Report friction or a bug directly to the borgmcp dev team. WRITE-ONLY \u2014 you cannot read reports back. Use it when something about borg itself slowed you down, confused you, or broke: awkward UX, an unclear playbook, a missing affordance, or a bug you hit while using borg. Secrets (tokens, keys) are auto-scrubbed server-side before storage, but avoid pasting them anyway.",inputSchema:{type:"object",properties:{message:{type:"string",description:"What hit you + what you expected instead (max 10KB). Concrete and specific helps the dev team most."},kind:{type:"string",enum:["friction","bug"],description:"'friction' (default) for UX/workflow friction; 'bug' for something broken."},metadata:{type:"object",description:"Optional non-secret context. Allowed keys only: version, cube_id, os. Any other key is rejected."}},required:["message"]}},{name:"borg_list-cubes",description:"List every cube owned by this user. Returns id, name, cube_directive, and timestamps for each. Useful before assimilate to see what's available, or as a starting point for any management action.",inputSchema:{type:"object",properties:{}}},{name:"borg_create-cube",description:'Create a new cube. The server seeds a default "Drone" role atomically so the cube is assimilatable immediately. Pass an optional `template` name to apply a richer role set instead (see borg_list-templates / borg_apply-template).',inputSchema:{type:"object",properties:{name:{type:"string",description:"Cube name (lowercase letters, digits, hyphens; max 64 chars).",pattern:"^[a-z0-9-]+$",maxLength:64},cube_directive:{type:"string",description:"Markdown text every drone in this cube will see in regen. Anything project-specific."},template:{type:"string",description:'Optional template name to apply after cube creation (e.g. "software-dev"). Roles are merged by name; the default Drone role gets overwritten by the template if a same-named role is in the template.'}},required:["name","cube_directive"]}},{name:"borg_update-cube",description:"Update a cube's name, cube_directive, and/or message_taxonomy. Pass only what changes.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to update."},name:{type:"string",description:"New name (optional). Lowercase letters, digits, hyphens; max 64 chars.",pattern:"^[a-z0-9-]+$",maxLength:64},cube_directive:{type:"string",description:"New cube directive markdown (optional)."},message_taxonomy:{type:"array",description:"New message-class taxonomy (optional). REPLACES the whole taxonomy; the worker re-validates the full array (non-overlapping prefixes, unique class names, directed classes need default_to). Pass [] to clear. To change ONE class without resending the whole array, use borg_patch-taxonomy-class instead. In default_to, pass @human-seat to route to drones in the cube human-seat role(s); literal role names/slugs/labels still work. Optional lifecycle tags mark dispatch/completion classes for stuck-dispatch detection.",items:{type:"object",properties:{class:{type:"string",description:"Unique class name."},prefixes:{type:"array",items:{type:"string"},description:"Message prefixes routed by this class."},routing:{type:"string",enum:["broadcast","directed"],description:"Routing mode."},default_to:{type:"array",items:{type:"string"},description:"Default recipients (role name/slug/label, or @human-seat) for a directed class."},lifecycle:{type:"string",enum:["dispatch","completion"],description:"Optional lifecycle marker for stuck-dispatch detection."}}}}},required:["cube_id"]}},{name:"borg_patch-taxonomy-class",description:"Patch ONE message-class in a cube's message_taxonomy without resending the whole taxonomy (avoids clobbering). action=add|replace|remove (replace/remove match name case-insensitively). The full taxonomy is re-validated after the patch (non-overlapping prefixes, unique names, directed classes need default_to) \u2014 a patch that breaks a rule against an untouched class is rejected. In default_to, @human-seat routes to the cube's human-seat role(s); literal names/slugs/labels also work. Optional lifecycle tags mark dispatch/completion classes for stuck-dispatch detection.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to patch."},action:{type:"string",enum:["add","replace","remove"],description:"add / replace / remove a single class."},class_def:{type:"object",description:'The class definition (for add/replace). Shape: { class, prefixes?, routing: "broadcast"|"directed", default_to?, lifecycle? }.',properties:{class:{type:"string",description:"Unique class name."},prefixes:{type:"array",items:{type:"string"},description:"Message prefixes routed by this class."},routing:{type:"string",enum:["broadcast","directed"],description:"Routing mode."},default_to:{type:"array",items:{type:"string"},description:"Default recipients (required for directed classes): role name/slug/label, or @human-seat."},lifecycle:{type:"string",enum:["dispatch","completion"],description:"Optional lifecycle marker for stuck-dispatch detection."}},required:["class","routing"]},class:{type:"string",description:"For remove only: the name of the class to drop (case-insensitive)."}},required:["cube_id","action"]}},{name:"borg_delete-cube",description:"Delete a cube and all its roles, drones, and log entries. Irreversible \u2014 confirm with the user before invoking unless the cube is clearly disposable.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to delete."}},required:["cube_id"]}},{name:"borg_create-role",description:"Create a role inside a cube. The detailed_description is the role's playbook \u2014 only drones assigned to this role see it. Setting is_default=true demotes any existing default; a cube has exactly one default role at a time.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube this role belongs to."},name:{type:"string",description:'Role name (e.g. "Builder", "Reviewer").'},short_description:{type:"string",description:"One-line summary, shown to every drone in the cube."},detailed_description:{type:"string",description:"Full playbook for drones in this role \u2014 workflow, conventions, log signals to post."},is_default:{type:"boolean",description:"If true, new drones assimilating into this cube are assigned this role. Demotes the previous default."},is_human_seat:{type:"boolean",description:"If true, this role represents the cube's human-occupied seat (where the human Queen sits directly). The class-hierarchy guard in reassign-drone allows promotion FROM a human-seat role TO the platform Queen role; promotion from non-human-seat roles is rejected."},can_broadcast:{type:"boolean",description:"If true, drones in this role may post broadcast log entries when strict broadcast gating is enabled."},receives_all_direct:{type:"boolean",description:"If true, drones in this role can see direct log entries as observer/audit recipients."},default_model:{type:"string",description:'Default model for drones assigned to this role (e.g., "claude:claude-opus-4-8" or "ollama:qwen3-coder-next:q4_K_M"). Null = inherit from cube. Optional.'}},required:["cube_id","name","short_description","detailed_description"]}},{name:"borg_update-role",description:"Update a role. Pass only the fields that change. Promoting to is_default demotes the previous default in the same cube.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to update."},name:{type:"string",description:"New role name (optional)."},short_description:{type:"string",description:"New short description (optional)."},detailed_description:{type:"string",description:"New detailed playbook (optional)."},is_default:{type:"boolean",description:"Set true to make this the cube's default role (optional)."},is_human_seat:{type:"boolean",description:"Set true/false to mark/unmark this as the cube's human-occupied seat (the elevation source for the platform Queen role)."},can_broadcast:{type:"boolean",description:"Set true/false to allow or deny broadcast log entries when strict broadcast gating is enabled."},receives_all_direct:{type:"boolean",description:"Set true/false to grant or remove observer visibility into direct log entries."},default_model:{type:"string",description:'Default model for drones assigned to this role (e.g., "claude:claude-opus-4-8" or "ollama:qwen3-coder-next:q4_K_M"). Null = inherit from cube. Optional.'}},required:["role_id"]}},{name:"borg_patch-role-section",description:"Surgically patch ONE named section of a role's detailed_description, leaving the rest of the field byte-identical. Sections are delimited by plain-label lines (e.g. `Workflow:`, `Project conventions:`) \u2014 NOT markdown headings; text before the first label is the preamble. Use this instead of borg_update-role when changing a single section so you don't have to resend (and risk clobbering) the whole playbook. action=replace overwrites a section's body; action=insert adds a new section (optionally after a named one, else appended); action=delete removes a section.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to patch."},action:{type:"string",enum:["replace","insert","delete"],description:"replace / insert / delete a single section."},heading:{type:"string",description:'The section label WITHOUT the trailing colon (e.g. "Workflow"). Matched case-insensitively.'},body:{type:"string",description:"New text BELOW the heading (for replace/insert). Omit for delete."},after:{type:"string",description:"For insert only: place the new section after the section with this heading. Omit/null to append at the end."}},required:["role_id","action","heading"]}},{name:"borg_delete-role",description:"Delete a role. Refuses if any drone is still assigned \u2014 reassign or evict those drones from the dashboard first.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to delete."}},required:["role_id"]}},{name:"borg_reassign-drone",description:"Reassign a drone to a different role in the same cube. Coordinator-shaped: the cube's Coordinator drone is the one expected to call this when dispatching new drones to specific work. Server refuses if you try to assign to the Coordinator role when another drone already holds it (evict or reassign that drone first).",inputSchema:{type:"object",properties:{drone_id:{type:"string",description:"UUID of the drone to reassign."},role_id:{type:"string",description:"UUID of the target role. Must belong to the same cube as the drone."}},required:["drone_id","role_id"]}},{name:"borg_evict-drone",description:"Evict (soft-delete) a drone from its cube. Coordinator-shaped: the cube's Coordinator/Queen seat calls this to remove a dead, stuck, or surplus drone \u2014 it drops out of the roster and frees its slot (incl. a held Coordinator/Queen-class seat), while its activity-log history is preserved with anonymized attribution. Owner-scoped: you can only evict drones in cubes you own. Identify the drone EITHER by drone_id (UUID) OR by label + cube_id (the label as it appears in the roster/regen).",inputSchema:{type:"object",properties:{drone_id:{type:"string",description:"UUID of the drone to evict. Provide this OR (label + cube_id)."},label:{type:"string",description:'Drone label to evict, e.g. "two-of-seventeen-builder". Requires cube_id. Ignored when drone_id is given.'},cube_id:{type:"string",description:"UUID of the cube the labelled drone belongs to. Required when evicting by label."}}}},{name:"borg_list-drones",description:"List every drone in a cube (owner-scoped). Returns id, label, role_id, agent_kind, last_seen, and wake_path_alert_class for each \u2014 gives the Coordinator a roster they can act on with borg_reassign-drone.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube whose drones to list."}},required:["cube_id"]}},{name:"borg_list-roles",description:"List every role in a cube (owner-scoped). Returns id, name, short_description, is_default, is_human_seat, can_broadcast, receives_all_direct, and role_class for each \u2014 gives Coordinator-class drones the role UUIDs they need for borg_reassign-drone (e.g. to promote a drone to the Queen role). Closes the gh#153 Queen-role-promotion UX gap (Coordinator drones previously had no way to discover role IDs without operator help).",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube whose roles to list."}},required:["cube_id"]}},{name:"borg_list-templates",description:"List available cube templates that can be applied via borg_apply-template or passed to borg_create-cube.",inputSchema:{type:"object",properties:{}}},{name:"borg_apply-template",description:"Apply a named template to an existing cube, NON-CLOBBERINGLY. Roles are merged by name: new roles are created; existing template-named roles get template sections/classes the cube LACKS auto-applied, but EVOLVED (conflicting) text is preserved, never overwritten. Use this to retrofit an existing cube with a richer role set (e.g. add Coordinator/Reviewer/UX Expert). To review + selectively accept conflicting fragments, use borg_sync-roles (which surfaces each conflict + takes per-fragment accept decisions).",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to apply the template to."},template_name:{type:"string",description:"Template to apply (see borg_list-templates)."}},required:["cube_id","template_name"]}},{name:"borg_sync-roles",description:"Non-clobbering sync of a cube's roles + message_taxonomy against the built-in template. Dry-run (default) classifies each fragment (role-text section, short_description, role flags, taxonomy class) as ADD (cube lacks it \u2014 safe auto-apply), UNCHANGED, or CONFLICT (cube has EVOLVED text). On apply, ADDs auto-apply; CONFLICTs apply ONLY via an explicit `decisions` accept (keyed on the dry-run fragment key, e.g. `role:Builder:section:Workflow`); unspecified conflicts default to reject \u2014 evolved text is NEVER silently overwritten. Custom roles untouched.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to sync."},template_name:{type:"string",description:"Template to sync against (default: software-dev)."},apply:{type:"boolean",description:"If true, commit (auto-apply ADDs + accepted conflicts). If false (default), dry-run only \u2014 classify + surface conflicts."},decisions:{type:"object",description:'Per-conflict accept/reject map, keyed on the fragment key from the dry-run (e.g. {"role:Builder:section:Workflow":"accept"}). Unspecified conflicts default to "reject" (keep the cube version).',additionalProperties:{type:"string",enum:["accept","reject"]}}},required:["cube_id"]}},{name:"borg_tool",description:`Dispatcher: invoke ANY borg tool by name, including tools not pre-loaded in your role-scoped surface. Pass {"name":"<borg_tool>","arguments":{...}}. Routes through the identical auth + validation path as a direct call. Call borg_describe-tool first to learn a deferred tool's arguments.`,inputSchema:{type:"object",properties:{name:{type:"string",description:'The borg tool to invoke, e.g. "borg_evict-drone".'},arguments:{type:"object",description:"The arguments object for that tool (same shape as a direct call)."}},required:["name"]}},{name:"borg_describe-tool",description:"Return the description + input schema for any borg tool by name \u2014 including deferred tools not pre-loaded in your surface. Schema-only; never executes the tool. Pair with borg_tool to invoke a deferred tool.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The borg tool to describe."}},required:["name"]}}];p.setRequestHandler(Y,async()=>{let u=null;try{const m=await y();m&&(u={roleName:m.roleName,roleClass:m.roleClass,isHumanSeat:m.isHumanSeat})}catch{u=null}return{tools:je(_,u)}}),p.setRequestHandler(X,async u=>{let{name:m,arguments:r}=u.params;if(m==="borg_describe-tool"){const e=typeof r?.name=="string"?r.name:"",t=_.find(i=>i.name===e);return t?{content:[{type:"text",text:JSON.stringify({name:t.name,description:t.description,inputSchema:t.inputSchema},null,2)}]}:{content:[{type:"text",text:`Unknown borg tool: ${e||"(none)"}. Pass { name: "<borg_tool>" }.`}],isError:!0}}if(m==="borg_tool"){const e=typeof r?.name=="string"?r.name:"";if(!e||e==="borg_tool"||e==="borg_describe-tool")return{content:[{type:"text",text:'borg_tool: pass { name: "<borg_tool>", arguments: {...} } naming a real borg tool (not the dispatcher itself).'}],isError:!0};r=r?.arguments&&typeof r.arguments=="object"?r.arguments:{},m=e}if(!Ge(`tool ${m}`))return{content:[{type:"text",text:Je(m)}],isError:!0};try{switch(m){case"borg_regen":{const e=await y();if(!e)return{content:[{type:"text",text:'Not connected to a cube. Use `borg_assimilate cube_name="<name>"` to join one.'}]};const t=typeof r?.since=="string"?r.since:void 0,i=r?.mode==="lite"?"lite":"full",o=await T(e.sessionToken,e.apiUrl,{since:t}),s=P(e,o);s!==e&&await A(s);const n=I(),a=q(s.cubeId,s.droneId),c=C()?!0:E(a),d=Ae(n,c)?Pe({inboxPath:a,droneLabel:Ce(o,s.droneLabel),cubeName:s.name}):"";let b="";try{const h=v(),l=Te();if(h!=="unknown"&&l!=="unknown"&&l!==h){const[g,R,Q]=h.split(".").map(Number),[k,D,V]=l.split(".").map(Number);(k>g||k===g&&D>R||k===g&&D===R&&V>Q)&&(b=`## \u{1F504} borgmcp ${l} installed \u2014 run /mcp and reconnect (or restart Claude Code) to apply. Currently running ${h}.
2
+ import{Server as K}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as z}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as X,ListToolsRequestSchema as Y,ListPromptsRequestSchema as G,GetPromptRequestSchema as J}from"@modelcontextprotocol/sdk/types.js";import{getCubeInfo as Z,getRoleInfo as j,getRoster as ee,readLog as te,appendLog as re,submitReport as oe,ackLogEntry as ie,regen as T,listCubes as ne,createCube as se,updateCube as O,deleteCube as ae,createRole as ce,updateRole as le,patchRoleSection as S,patchTaxonomyClass as N,deleteRole as de,reassignDrone as pe,evictDrone as ue,getCube as w,checkSubscriptionStatus as me,createBillingPortalSession as be,createSubscription as he,syncRoles as ge,applyTemplate as ye,whoami as fe,roleRationale as _e,getValidToken as we}from"./remote-client.js";import{startHealthBeatTick as ve}from"./health-beat.js";import{getTemplate as $,listTemplateNames as U,resolveCubeDirectiveForCreate as xe,resolveCubeDirectiveForApply as ke,resolveMessageTaxonomyForCreate as Se}from"./templates.js";import{activeCubeWithFreshRegenIdentity as P,getActiveCube as y,setActiveCube as A,inboxPathForDrone as q}from"./cubes.js";import{addSessionStartHook as $e,addUserPromptSubmitHook as Ue}from"./config-utils.js";import{humanAgo as L,formatLogEntryMarkdown as qe,formatRegenMarkdown as M,getDronePlaybook as Ee,getDronePlaybookChapter as Ie,nullTaxonomyTip as Ce,regenWakePathDroneLabel as Re}from"./regen-format.js";import{startLogStream as De,getStreamStatus as E}from"./log-stream.js";import{renderRoleList as je}from"./list-roles-render.js";import{filterToolsForRole as Te}from"./tool-scope.js";import{getPackageVersion as v,getOnDiskVersion as Oe,handleVersionFlag as Ne}from"./version.js";import{renderStreamStatus as Pe,checkInboxMonitorHealthy as I,formatWakePathPrefix as Ae,shouldShowWakePathWarning as Le}from"./stream-status.js";import{formatRoleAgentLabel as Me,renderRoster as Be}from"./roster-render.js";import{resolveDroneIdByLabel as Fe,isUuidShape as We}from"./evict-drone.js";import{authRecoveryMessage as He}from"./auth-recovery.js";import{DroneEvictedError as Qe,DroneFrozenError as Ve,formatEvictedToolResult as Ke,formatFrozenToolResult as ze}from"./drone-lifecycle.js";import{classifyInSessionAssimilate as Xe,reattachOnlyRefusal as Ye,reattachFailureMessage as Ge}from"./assimilate-guard.js";import{gateAllowsActivation as Je,borgSessionToolNotice as Ze}from"./launch-gate.js";import{renderSyncRolesResult as et}from"./sync-roles-render.js";import{initConsolePrefix as tt,consolePrefix as x}from"./console-prefix.js";import{isCodexRemoteWakeEnabled as C,resolveSessionAgentKind as rt,probeCodexBridgeArmed as ot}from"./codex-app-wake.js";import{lifecycleSignalForMessage as it,recordLifecycleLog as B,shouldSuppressLifecycleLog as nt}from"./lifecycle-log-guard.js";import{normalizeDirectLogRecipients as st}from"./direct-log.js";import F from"open";import at from"os";function ct(){try{const p=at.hostname();return p&&p.trim()?p.trim().slice(0,255):null}catch{return null}}async function W(p,_){return await ye(p,_.name)}async function f(){const p=await y();if(!p)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");return p}async function lt(){Ne();try{$e()}catch{}try{Ue()}catch{}try{De()}catch{}try{ve({getActiveCube:y,getStreamConnected:()=>E().connected,getInboxPath:u=>q(u.cubeId,u.droneId),checkMonitor:I,isCodexRemoteWake:C,probeBridgeArmed:u=>ot({cubeId:u.cubeId,droneId:u.droneId}),resolveAgentKind:rt,resolveHostname:ct,resolveVersion:v,getToken:we,fetchImpl:globalThis.fetch.bind(globalThis)})}catch{}const p=new K({name:"borg-mcp-client",version:v()},{capabilities:{tools:{},prompts:{}}}),_=[{name:"borg_subscribe",description:"Create Stripe checkout session for Cube tier ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr). Free tier is permanent (1 cube + 3 agent sessions + 100 req/hr); no trial.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_upgrade-subscription",description:"Open the Stripe Billing Portal to manage Cube tier quantity ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr).",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_subscription_status",description:"Check subscription status",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_open_dashboard",description:"Open Borg MCP dashboard in browser to manage cubes, roles, and drones",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_regen",description:"Refresh your context as a Drone. Returns the active cube's directive, your role's detailed playbook, the drone roster, and recent activity log entries \u2014 everything you need to be oriented. Call on session start, and again before each new task to stay in sync with the cube. Returns \"not connected\" if no active cube; use borg_assimilate first in that case. Optional `since` (entry-id UUID or ISO-8601 timestamp) trims the recent-log section to entries strictly after the anchor \u2014 pass your last-seen entry id to skip already-processed history on each refresh.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional cursor. Either an activity_log entry id (UUID; server resolves to (created_at, id) tuple) OR an ISO-8601 timestamp. When provided, the recent-log section returns entries strictly after that anchor. Non-existent UUID falls back to default recent window."},mode:{type:"string",enum:["full","lite"],description:"Optional output mode. Use full at session start and after context compaction. Lite omits unchanged role playbook/directive/boilerplate while always showing dynamic safety information and recent activity."}},required:[]}},{name:"borg_assimilate",description:"RE-ATTACH this session to the drone seat already saved for this worktree (gh#780: this tool never creates seats). Provide the cube's name; on a match it returns the cube directive, your role's instructions, and recent activity for the EXISTING seat. To create a seat or switch cubes, run `borg assimilate` in a terminal instead.",inputSchema:{type:"object",properties:{cube_name:{type:"string",description:"The cube to connect to"}},required:["cube_name"]}},{name:"borg_cube",description:"Read the active Cube's directive and the registry of all roles in it (each role's name + short description). Use to remind yourself of cube-wide context.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_role",description:"Read your assigned role's detailed description (your playbook). Other drones cannot see this \u2014 only you (drones in this role).",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_version",description:"Returns the installed borgmcp client version. Use to verify which version is running in this MCP session.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_playbook",description:"Load the full operating-playbook chapter \u2014 the detailed disciplines, rationale, examples, and case studies behind the rule-spine in your regen (verification discipline v1/v2/v3, concrete source-of-truth surfaces, four-surface propagation, empirical case studies). gh#912: this detail is kept OUT of the regen bootstrap to keep it light; fetch it ONCE per session when doing review/verify-class work. Static text \u2014 do NOT re-fetch on every wake.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_whoami",description:"Returns your identity in the current cube: cube name, drone label, and role name. Use to confirm which cube/role/drone you are.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_role-rationale",description:"Fetch an on-demand rationale/case-study section for a role playbook. Pass a role name/id and a plain-label section key to read the rationale without expanding every regen.",inputSchema:{type:"object",properties:{role:{type:"string",description:"Role name or role id to fetch rationale for, e.g. Builder."},section:{type:"string",description:"Plain-label role section key, e.g. Workflow rationale."}},required:["role","section"]}},{name:"borg_roster",description:"List all currently connected drones in your cube, with each drone's label, role, and last-seen time. Optional `since` argument adds a sender-side liveness column \u2014 pass either an activity_log entry id (e.g., from a dispatch you posted) or an ISO-8601 timestamp; each drone is marked `awake` if they've posted a log entry after that point, otherwise `stale-since-X`. Useful for confirming a dispatch reached its named recipients (catches the silent-wake-path-failure class where SSE delivered but the drone's /loop never woke).",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional liveness reference point. Either an activity_log entry id (UUID; server resolves to its created_at) OR an ISO-8601 timestamp. When provided, each drone in the output is tagged awake/stale relative to that point."}},required:[]}},{name:"borg_stream-status",description:"Diagnostic probe of the local SSE log-stream consumer: returns `connected`, `lastContentEventAt`, `lastWireActivityAt`, `lastHeartbeatAt`, `lastPersistedEventId`, `reconnectAttempts`, plus a wake-path check that flags if SSE is attached but no inbox-Monitor is watching the file (the silent failure where `/loop` never wakes on incoming entries). Read-only in-process state; does NOT re-open the stream. Use when troubleshooting wake-ups or verifying the stream is alive.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_read-log",description:"Read entries from the cube's activity log. Each entry is tagged with the drone that wrote it and that drone's role. For wake triage, prefer `unread_only=true` with a modest limit and drain until `has_more=false`; this reads oldest-unread-first from your server cursor and advances the watermark so bursts are not skipped. Optional `since` is a strict-after cursor for explicit bounded reads only; do not use it with the same timestamp as a notification preview because it can skip the boundary entry.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional strict-after cursor for explicit bounded reads. Either an activity_log entry id (UUID; server resolves to (created_at, id) tuple for deterministic tie-break) OR an ISO-8601 timestamp. Do not use for routine wake triage; prefer unread_only."},limit:{type:"number",description:"max entries to return (1-500)"},unread_only:{type:"boolean",description:"When true, read only entries posted after this drone last called read-log, oldest-unread-first. Server advances the watermark to the newest returned entry on every call; if has_more=true, call again until has_more=false."}}}},{name:"borg_ack",description:"Mark a log entry as explicitly acknowledged. Replaces the convention of posting `ACK: <dispatch-id>` log entries. The ack is recorded in a queryable DB flag (activity_log_acks) keyed on (entry_id, drone_id, kind). Idempotent \u2014 repeated calls on the same entry are no-ops. Use this whenever a previous workflow would have prompted you to log an ACK; it removes the noise from the cube log while keeping the signal queryable.",inputSchema:{type:"object",required:["entry_id"],properties:{entry_id:{type:"string",description:"UUID of the log entry to acknowledge."}}}},{name:"borg_log",description:"Append a message to the cube's activity log. By default entries broadcast to all drones. When a cube declares a message taxonomy, borg_log applies class-based smart defaults: prefix-matched directed classes route to their default recipients unless you pass `to:`, `class:`, or explicit visibility. Pass `to: [...]` to direct by exact drone label, drone id, role name, or role slug.",inputSchema:{type:"object",properties:{message:{type:"string",description:"The log message (max 10KB)."},to:{type:"array",items:{type:"string"},description:"Optional direct-message recipients by exact drone label, drone id, role name, or role slug (resolves to all drones in that role). Omit to let class-based routing or broadcast defaults apply."},class:{type:"string",description:"Optional declared message class. Overrides prefix auto-classification when the cube declares a message taxonomy."},visibility:{type:"string",enum:["broadcast","direct"],description:"Optional explicit visibility. Overrides class-based routing defaults."}},required:["message"]}},{name:"borg_report-friction",description:"Report friction or a bug directly to the borgmcp dev team. WRITE-ONLY \u2014 you cannot read reports back. Use it when something about borg itself slowed you down, confused you, or broke: awkward UX, an unclear playbook, a missing affordance, or a bug you hit while using borg. Secrets (tokens, keys) are auto-scrubbed server-side before storage, but avoid pasting them anyway.",inputSchema:{type:"object",properties:{message:{type:"string",description:"What hit you + what you expected instead (max 10KB). Concrete and specific helps the dev team most."},kind:{type:"string",enum:["friction","bug"],description:"'friction' (default) for UX/workflow friction; 'bug' for something broken."},metadata:{type:"object",description:"Optional non-secret context. Allowed keys only: version, cube_id, os. Any other key is rejected."}},required:["message"]}},{name:"borg_list-cubes",description:"List every cube owned by this user. Returns id, name, cube_directive, and timestamps for each. Useful before assimilate to see what's available, or as a starting point for any management action.",inputSchema:{type:"object",properties:{}}},{name:"borg_create-cube",description:'Create a new cube. The server seeds a default "Drone" role atomically so the cube is assimilatable immediately. Pass an optional `template` name to apply a richer role set instead (see borg_list-templates / borg_apply-template).',inputSchema:{type:"object",properties:{name:{type:"string",description:"Cube name (lowercase letters, digits, hyphens; max 64 chars).",pattern:"^[a-z0-9-]+$",maxLength:64},cube_directive:{type:"string",description:"Markdown text every drone in this cube will see in regen. Anything project-specific."},template:{type:"string",description:'Optional template name to apply after cube creation (e.g. "software-dev"). Roles are merged by name; the default Drone role gets overwritten by the template if a same-named role is in the template.'}},required:["name","cube_directive"]}},{name:"borg_update-cube",description:"Update a cube's name, cube_directive, and/or message_taxonomy. Pass only what changes.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to update."},name:{type:"string",description:"New name (optional). Lowercase letters, digits, hyphens; max 64 chars.",pattern:"^[a-z0-9-]+$",maxLength:64},cube_directive:{type:"string",description:"New cube directive markdown (optional)."},message_taxonomy:{type:"array",description:"New message-class taxonomy (optional). REPLACES the whole taxonomy; the worker re-validates the full array (non-overlapping prefixes, unique class names, directed classes need default_to). Pass [] to clear. To change ONE class without resending the whole array, use borg_patch-taxonomy-class instead. In default_to, pass @human-seat to route to drones in the cube human-seat role(s); literal role names/slugs/labels still work. Optional lifecycle tags mark dispatch/completion classes for stuck-dispatch detection.",items:{type:"object",properties:{class:{type:"string",description:"Unique class name."},prefixes:{type:"array",items:{type:"string"},description:"Message prefixes routed by this class."},routing:{type:"string",enum:["broadcast","directed"],description:"Routing mode."},default_to:{type:"array",items:{type:"string"},description:"Default recipients (role name/slug/label, or @human-seat) for a directed class."},lifecycle:{type:"string",enum:["dispatch","completion"],description:"Optional lifecycle marker for stuck-dispatch detection."}}}}},required:["cube_id"]}},{name:"borg_patch-taxonomy-class",description:"Patch ONE message-class in a cube's message_taxonomy without resending the whole taxonomy (avoids clobbering). action=add|replace|remove (replace/remove match name case-insensitively). The full taxonomy is re-validated after the patch (non-overlapping prefixes, unique names, directed classes need default_to) \u2014 a patch that breaks a rule against an untouched class is rejected. In default_to, @human-seat routes to the cube's human-seat role(s); literal names/slugs/labels also work. Optional lifecycle tags mark dispatch/completion classes for stuck-dispatch detection.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to patch."},action:{type:"string",enum:["add","replace","remove"],description:"add / replace / remove a single class."},class_def:{type:"object",description:'The class definition (for add/replace). Shape: { class, prefixes?, routing: "broadcast"|"directed", default_to?, lifecycle? }.',properties:{class:{type:"string",description:"Unique class name."},prefixes:{type:"array",items:{type:"string"},description:"Message prefixes routed by this class."},routing:{type:"string",enum:["broadcast","directed"],description:"Routing mode."},default_to:{type:"array",items:{type:"string"},description:"Default recipients (required for directed classes): role name/slug/label, or @human-seat."},lifecycle:{type:"string",enum:["dispatch","completion"],description:"Optional lifecycle marker for stuck-dispatch detection."}},required:["class","routing"]},class:{type:"string",description:"For remove only: the name of the class to drop (case-insensitive)."}},required:["cube_id","action"]}},{name:"borg_delete-cube",description:"Delete a cube and all its roles, drones, and log entries. Irreversible \u2014 confirm with the user before invoking unless the cube is clearly disposable.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to delete."}},required:["cube_id"]}},{name:"borg_create-role",description:"Create a role inside a cube. The detailed_description is the role's playbook \u2014 only drones assigned to this role see it. Setting is_default=true demotes any existing default; a cube has exactly one default role at a time.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube this role belongs to."},name:{type:"string",description:'Role name (e.g. "Builder", "Reviewer").'},short_description:{type:"string",description:"One-line summary, shown to every drone in the cube."},detailed_description:{type:"string",description:"Full playbook for drones in this role \u2014 workflow, conventions, log signals to post."},is_default:{type:"boolean",description:"If true, new drones assimilating into this cube are assigned this role. Demotes the previous default."},is_human_seat:{type:"boolean",description:"If true, this role represents the cube's human-occupied seat (where the human Queen sits directly). The class-hierarchy guard in reassign-drone allows promotion FROM a human-seat role TO the platform Queen role; promotion from non-human-seat roles is rejected."},can_broadcast:{type:"boolean",description:"If true, drones in this role may post broadcast log entries when strict broadcast gating is enabled."},receives_all_direct:{type:"boolean",description:"If true, drones in this role can see direct log entries as observer/audit recipients."},default_model:{type:"string",description:'Default model for drones assigned to this role (e.g., "claude:claude-opus-4-8" or "ollama:qwen3-coder-next:q4_K_M"). Null = inherit from cube. Optional.'}},required:["cube_id","name","short_description","detailed_description"]}},{name:"borg_update-role",description:"Update a role. Pass only the fields that change. Promoting to is_default demotes the previous default in the same cube.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to update."},name:{type:"string",description:"New role name (optional)."},short_description:{type:"string",description:"New short description (optional)."},detailed_description:{type:"string",description:"New detailed playbook (optional)."},is_default:{type:"boolean",description:"Set true to make this the cube's default role (optional)."},is_human_seat:{type:"boolean",description:"Set true/false to mark/unmark this as the cube's human-occupied seat (the elevation source for the platform Queen role)."},can_broadcast:{type:"boolean",description:"Set true/false to allow or deny broadcast log entries when strict broadcast gating is enabled."},receives_all_direct:{type:"boolean",description:"Set true/false to grant or remove observer visibility into direct log entries."},default_model:{type:"string",description:'Default model for drones assigned to this role (e.g., "claude:claude-opus-4-8" or "ollama:qwen3-coder-next:q4_K_M"). Null = inherit from cube. Optional.'}},required:["role_id"]}},{name:"borg_patch-role-section",description:"Surgically patch ONE named section of a role's detailed_description, leaving the rest of the field byte-identical. Sections are delimited by plain-label lines (e.g. `Workflow:`, `Project conventions:`) \u2014 NOT markdown headings; text before the first label is the preamble. Use this instead of borg_update-role when changing a single section so you don't have to resend (and risk clobbering) the whole playbook. action=replace overwrites a section's body; action=insert adds a new section (optionally after a named one, else appended); action=delete removes a section.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to patch."},action:{type:"string",enum:["replace","insert","delete"],description:"replace / insert / delete a single section."},heading:{type:"string",description:'The section label WITHOUT the trailing colon (e.g. "Workflow"). Matched case-insensitively.'},body:{type:"string",description:"New text BELOW the heading (for replace/insert). Omit for delete."},after:{type:"string",description:"For insert only: place the new section after the section with this heading. Omit/null to append at the end."}},required:["role_id","action","heading"]}},{name:"borg_delete-role",description:"Delete a role. Refuses if any drone is still assigned \u2014 reassign or evict those drones from the dashboard first.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to delete."}},required:["role_id"]}},{name:"borg_reassign-drone",description:"Reassign a drone to a different role in the same cube. Coordinator-shaped: the cube's Coordinator drone is the one expected to call this when dispatching new drones to specific work. Server refuses if you try to assign to the Coordinator role when another drone already holds it (evict or reassign that drone first).",inputSchema:{type:"object",properties:{drone_id:{type:"string",description:"UUID of the drone to reassign."},role_id:{type:"string",description:"UUID of the target role. Must belong to the same cube as the drone."}},required:["drone_id","role_id"]}},{name:"borg_evict-drone",description:"Evict (soft-delete) a drone from its cube. Coordinator-shaped: the cube's Coordinator/Queen seat calls this to remove a dead, stuck, or surplus drone \u2014 it drops out of the roster and frees its slot (incl. a held Coordinator/Queen-class seat), while its activity-log history is preserved with anonymized attribution. Owner-scoped: you can only evict drones in cubes you own. Identify the drone EITHER by drone_id (UUID) OR by label + cube_id (the label as it appears in the roster/regen).",inputSchema:{type:"object",properties:{drone_id:{type:"string",description:"UUID of the drone to evict. Provide this OR (label + cube_id)."},label:{type:"string",description:'Drone label to evict, e.g. "two-of-seventeen-builder". Requires cube_id. Ignored when drone_id is given.'},cube_id:{type:"string",description:"UUID of the cube the labelled drone belongs to. Required when evicting by label."}}}},{name:"borg_list-drones",description:"List every drone in a cube (owner-scoped). Returns id, label, role_id, agent_kind, last_seen, and wake_path_alert_class for each \u2014 gives the Coordinator a roster they can act on with borg_reassign-drone.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube whose drones to list."}},required:["cube_id"]}},{name:"borg_list-roles",description:"List every role in a cube (owner-scoped). Returns id, name, short_description, is_default, is_human_seat, can_broadcast, receives_all_direct, and role_class for each \u2014 gives Coordinator-class drones the role UUIDs they need for borg_reassign-drone (e.g. to promote a drone to the Queen role). Closes the gh#153 Queen-role-promotion UX gap (Coordinator drones previously had no way to discover role IDs without operator help).",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube whose roles to list."}},required:["cube_id"]}},{name:"borg_list-templates",description:"List available cube templates that can be applied via borg_apply-template or passed to borg_create-cube.",inputSchema:{type:"object",properties:{}}},{name:"borg_apply-template",description:"Apply a named template to an existing cube, NON-CLOBBERINGLY. Roles are merged by name: new roles are created; existing template-named roles get template sections/classes the cube LACKS auto-applied, but EVOLVED (conflicting) text is preserved, never overwritten. Use this to retrofit an existing cube with a richer role set (e.g. add Coordinator/Reviewer/UX Expert). To review + selectively accept conflicting fragments, use borg_sync-roles (which surfaces each conflict + takes per-fragment accept decisions).",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to apply the template to."},template_name:{type:"string",description:"Template to apply (see borg_list-templates)."}},required:["cube_id","template_name"]}},{name:"borg_sync-roles",description:"Non-clobbering sync of a cube's roles + message_taxonomy against the built-in template. Dry-run (default) classifies each fragment (role-text section, short_description, role flags, taxonomy class) as ADD (cube lacks it \u2014 safe auto-apply), UNCHANGED, or CONFLICT (cube has EVOLVED text). On apply, ADDs auto-apply; CONFLICTs apply ONLY via an explicit `decisions` accept (keyed on the dry-run fragment key, e.g. `role:Builder:section:Workflow`); unspecified conflicts default to reject \u2014 evolved text is NEVER silently overwritten. Custom roles untouched.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to sync."},template_name:{type:"string",description:"Template to sync against (default: software-dev)."},apply:{type:"boolean",description:"If true, commit (auto-apply ADDs + accepted conflicts). If false (default), dry-run only \u2014 classify + surface conflicts."},decisions:{type:"object",description:'Per-conflict accept/reject map, keyed on the fragment key from the dry-run (e.g. {"role:Builder:section:Workflow":"accept"}). Unspecified conflicts default to "reject" (keep the cube version).',additionalProperties:{type:"string",enum:["accept","reject"]}}},required:["cube_id"]}},{name:"borg_tool",description:`Dispatcher: invoke ANY borg tool by name, including tools not pre-loaded in your role-scoped surface. Pass {"name":"<borg_tool>","arguments":{...}}. Routes through the identical auth + validation path as a direct call. Call borg_describe-tool first to learn a deferred tool's arguments.`,inputSchema:{type:"object",properties:{name:{type:"string",description:'The borg tool to invoke, e.g. "borg_evict-drone".'},arguments:{type:"object",description:"The arguments object for that tool (same shape as a direct call)."}},required:["name"]}},{name:"borg_describe-tool",description:"Return the description + input schema for any borg tool by name \u2014 including deferred tools not pre-loaded in your surface. Schema-only; never executes the tool. Pair with borg_tool to invoke a deferred tool.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The borg tool to describe."}},required:["name"]}}];p.setRequestHandler(Y,async()=>{let u=null;try{const m=await y();m&&(u={roleName:m.roleName,roleClass:m.roleClass,isHumanSeat:m.isHumanSeat})}catch{u=null}return{tools:Te(_,u)}}),p.setRequestHandler(X,async u=>{let{name:m,arguments:r}=u.params;if(m==="borg_describe-tool"){const e=typeof r?.name=="string"?r.name:"",t=_.find(i=>i.name===e);return t?{content:[{type:"text",text:JSON.stringify({name:t.name,description:t.description,inputSchema:t.inputSchema},null,2)}]}:{content:[{type:"text",text:`Unknown borg tool: ${e||"(none)"}. Pass { name: "<borg_tool>" }.`}],isError:!0}}if(m==="borg_tool"){const e=typeof r?.name=="string"?r.name:"";if(!e||e==="borg_tool"||e==="borg_describe-tool")return{content:[{type:"text",text:'borg_tool: pass { name: "<borg_tool>", arguments: {...} } naming a real borg tool (not the dispatcher itself).'}],isError:!0};r=r?.arguments&&typeof r.arguments=="object"?r.arguments:{},m=e}if(!Je(`tool ${m}`))return{content:[{type:"text",text:Ze(m)}],isError:!0};try{switch(m){case"borg_regen":{const e=await y();if(!e)return{content:[{type:"text",text:'Not connected to a cube. Use `borg_assimilate cube_name="<name>"` to join one.'}]};const t=typeof r?.since=="string"?r.since:void 0,i=r?.mode==="lite"?"lite":"full",o=await T(e.sessionToken,e.apiUrl,{since:t}),s=P(e,o);s!==e&&await A(s);const n=E(),a=q(s.cubeId,s.droneId),c=C()?!0:I(a),d=Le(n,c)?Ae({inboxPath:a,droneLabel:Re(o,s.droneLabel),cubeName:s.name}):"";let b="";try{const h=v(),l=Oe();if(h!=="unknown"&&l!=="unknown"&&l!==h){const[g,R,Q]=h.split(".").map(Number),[k,D,V]=l.split(".").map(Number);(k>g||k===g&&D>R||k===g&&D===R&&V>Q)&&(b=`## \u{1F504} borgmcp ${l} installed \u2014 run /mcp and reconnect (or restart Claude Code) to apply. Currently running ${h}.
3
3
 
4
- `)}}catch{}return{content:[{type:"text",text:b+d+M(o,{mode:i})}]}}case"borg_subscribe":return{content:[{type:"text",text:`Complete your subscription at: ${await he()}`}]};case"borg_upgrade-subscription":{const e=await be();try{await F(e)}catch{}return{content:[{type:"text",text:`Manage your Borg MCP subscription at: ${e}`}]}}case"borg_subscription_status":{const e=await me();return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}case"borg_open_dashboard":{const e="https://borgmcp.ai/dashboard";return await F(e),{content:[{type:"text",text:`\u25FC Opened dashboard in browser: ${e}`}]}}case"borg_assimilate":{const e=r?.cube_name;if(!e)throw new Error("cube_name is required");const t=await y(),i=ze(t,e);if(i.kind!=="reattach")return{content:[{type:"text",text:Xe(i,e)}],isError:!0};try{const o=await T(t.sessionToken,t.apiUrl,{}),s=P(t,o);return s!==t&&await A(s),{content:[{type:"text",text:[`# Re-attached to cube: ${s.name}`,"",`**Drone label:** ${s.droneLabel}`,"**Seat:** existing identity reused \u2014 no new drone minted (gh#780)","",""].join(`
5
- `)+M(o,{mode:"full"})}]}}catch(o){const s=Ye(o??{});if(!s)throw o;return{content:[{type:"text",text:s}],isError:!0}}}case"borg_version":return{content:[{type:"text",text:`borgmcp ${v()}`}]};case"borg_whoami":{const e=await f(),t=await fe(e.sessionToken,e.apiUrl);return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}case"borg_cube":{const e=await f(),[{cube:t,roles:i}]=await Promise.all([Z(e.sessionToken,e.apiUrl),j(e.sessionToken,e.apiUrl)]),o=[];o.push(`# Cube: ${t.name}`),o.push(""),o.push("## Cube directive"),o.push(t.cube_directive||"_(none)_"),o.push("");const s=Ee(t.message_taxonomy);if(s&&(o.push(s),o.push("")),o.push("## Roles in this cube"),!i.length)o.push("_(no roles defined)_");else{for(const n of i){const a=[n.role_class==="queen"?"Queen":null,n.is_human_seat?"human-seat":null,n.is_default?"default":null].filter(Boolean).join(", "),c=a?` (${a})`:"",d=n.short_description||"_(no description)_";o.push(`- **${n.name}**${c} \u2014 ${d}`)}o.push(""),o.push("_(Coordinator-class drones can fetch role IDs via `borg_list-roles` for use with `borg_reassign-drone`.)_")}return o.push(""),o.push(Ie()),{content:[{type:"text",text:o.join(`
4
+ `)}}catch{}return{content:[{type:"text",text:b+d+M(o,{mode:i})}]}}case"borg_subscribe":return{content:[{type:"text",text:`Complete your subscription at: ${await he()}`}]};case"borg_upgrade-subscription":{const e=await be();try{await F(e)}catch{}return{content:[{type:"text",text:`Manage your Borg MCP subscription at: ${e}`}]}}case"borg_subscription_status":{const e=await me();return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}case"borg_open_dashboard":{const e="https://borgmcp.ai/dashboard";return await F(e),{content:[{type:"text",text:`\u25FC Opened dashboard in browser: ${e}`}]}}case"borg_assimilate":{const e=r?.cube_name;if(!e)throw new Error("cube_name is required");const t=await y(),i=Xe(t,e);if(i.kind!=="reattach")return{content:[{type:"text",text:Ye(i,e)}],isError:!0};try{const o=await T(t.sessionToken,t.apiUrl,{}),s=P(t,o);return s!==t&&await A(s),{content:[{type:"text",text:[`# Re-attached to cube: ${s.name}`,"",`**Drone label:** ${s.droneLabel}`,"**Seat:** existing identity reused \u2014 no new drone minted (gh#780)","",""].join(`
5
+ `)+M(o,{mode:"full"})}]}}catch(o){const s=Ge(o??{});if(!s)throw o;return{content:[{type:"text",text:s}],isError:!0}}}case"borg_version":return{content:[{type:"text",text:`borgmcp ${v()}`}]};case"borg_playbook":return{content:[{type:"text",text:Ie()}]};case"borg_whoami":{const e=await f(),t=await fe(e.sessionToken,e.apiUrl);return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}case"borg_cube":{const e=await f(),[{cube:t,roles:i}]=await Promise.all([Z(e.sessionToken,e.apiUrl),j(e.sessionToken,e.apiUrl)]),o=[];o.push(`# Cube: ${t.name}`),o.push(""),o.push("## Cube directive"),o.push(t.cube_directive||"_(none)_"),o.push("");const s=Ce(t.message_taxonomy);if(s&&(o.push(s),o.push("")),o.push("## Roles in this cube"),!i.length)o.push("_(no roles defined)_");else{for(const n of i){const a=[n.role_class==="queen"?"Queen":null,n.is_human_seat?"human-seat":null,n.is_default?"default":null].filter(Boolean).join(", "),c=a?` (${a})`:"",d=n.short_description||"_(no description)_";o.push(`- **${n.name}**${c} \u2014 ${d}`)}o.push(""),o.push("_(Coordinator-class drones can fetch role IDs via `borg_list-roles` for use with `borg_reassign-drone`.)_")}return o.push(""),o.push(Ee()),{content:[{type:"text",text:o.join(`
6
6
  `)}]}}case"borg_role":{const e=await f(),{role:t}=await j(e.sessionToken,e.apiUrl);return{content:[{type:"text",text:[`# Your role: ${t.name}`,"",t.detailed_description||"_(no detailed description set)_"].join(`
7
7
  `)}]}}case"borg_role-rationale":{const e=await f(),t=typeof r?.role=="string"?r.role:"",i=typeof r?.section=="string"?r.section:"",o=await _e(e.sessionToken,e.apiUrl,t,i);return{content:[{type:"text",text:[`# Role rationale: ${o.role} \u2014 ${o.section}`,"",o.body||"_(empty)_"].join(`
8
- `)}]}}case"borg_roster":{const e=await f(),t=typeof r?.since=="string"?r.since:void 0,{drones:i,roles:o,since:s}=await ee(e.sessionToken,e.apiUrl,t);return{content:[{type:"text",text:Me({cubeName:e.name,drones:i,roles:o,resolvedSince:s??null,humanAgo:L})}]}}case"borg_stream-status":{const e=I(),t=await y(),i=t?q(t.cubeId,t.droneId):null,o=t?C()?!0:E(i):null;let s="";e.runLoopHealth==="silent-inert"&&(s=`## \u26A0 SSE stream loop silent-inert \u2014 run /mcp and reconnect to restart
8
+ `)}]}}case"borg_roster":{const e=await f(),t=typeof r?.since=="string"?r.since:void 0,{drones:i,roles:o,since:s}=await ee(e.sessionToken,e.apiUrl,t);return{content:[{type:"text",text:Be({cubeName:e.name,drones:i,roles:o,resolvedSince:s??null,humanAgo:L})}]}}case"borg_stream-status":{const e=E(),t=await y(),i=t?q(t.cubeId,t.droneId):null,o=t?C()?!0:I(i):null;let s="";e.runLoopHealth==="silent-inert"&&(s=`## \u26A0 SSE stream loop silent-inert \u2014 run /mcp and reconnect to restart
9
9
 
10
10
  The log-stream consumer started but never connected. This drone will not receive real-time cube events.
11
11
 
12
- `);const n=Ne({status:e,inboxMonitorHealthy:o,inboxPath:i,droneLabel:t?.droneLabel??null,cubeName:t?.name??null,humanAgo:L});return{content:[{type:"text",text:s+n}]}}case"borg_read-log":{const e=await f(),t=typeof r?.since=="string"?r.since:void 0,i=typeof r?.limit=="number"?r.limit:void 0,o=r?.unread_only===!0||r?.unread_only==="true",{entries:s,drones:n,roles:a,behind_by:c,has_more:d}=await te(e.sessionToken,e.apiUrl,{since:t,limit:i,unreadOnly:o}),b=new Map;for(const g of n)b.set(g.id,g);const h=new Map;for(const g of a)h.set(g.id,g);const l=[];if(l.push(`# Activity log: ${e.name}`),l.push(""),!s.length)l.push("_(no entries)_");else for(const g of s)l.push(qe(g,b,h));return d===!0?(l.push(""),l.push("\u26A0 has_more: true \u2014 call `borg_read-log unread_only=true` again until has_more=false so you finish draining unread entries.")):typeof c=="number"&&c>0&&(l.push(""),l.push(`\u26A0 behind_by: ${c} more unread ${c===1?"entry":"entries"} addressed to you \u2014 call \`borg_read-log unread_only=true\` again until behind_by=0 so you don't skip messages.`)),{content:[{type:"text",text:l.join(`
13
- `)}]}}case"borg_log":{const e=r?.message;if(!e||typeof e!="string")throw new Error("message is required");const t=await y();if(!t)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");if(ot(e)){const l=await it(t,e);if(l.suppress)return await B(t,e),{content:[{type:"text",text:`Suppressed duplicate ${l.signal?.toUpperCase()} lifecycle log for ${t.droneLabel}; recent cube log already contains this signal.`}]}}const i=Object.prototype.hasOwnProperty.call(r??{},"to"),o=i?nt(r?.to):void 0,s=typeof r?.class=="string"?r.class:void 0,n=r?.visibility==="broadcast"||r?.visibility==="direct"?r.visibility:void 0,a={...s?{class:s}:{},...i?{to:o??[]}:{},...n?{visibility:n}:{}},c=await re(t.sessionToken,t.apiUrl,e,a);await B(t,e);const d=c.routing?.message?`
12
+ `);const n=Pe({status:e,inboxMonitorHealthy:o,inboxPath:i,droneLabel:t?.droneLabel??null,cubeName:t?.name??null,humanAgo:L});return{content:[{type:"text",text:s+n}]}}case"borg_read-log":{const e=await f(),t=typeof r?.since=="string"?r.since:void 0,i=typeof r?.limit=="number"?r.limit:void 0,o=r?.unread_only===!0||r?.unread_only==="true",{entries:s,drones:n,roles:a,behind_by:c,has_more:d}=await te(e.sessionToken,e.apiUrl,{since:t,limit:i,unreadOnly:o}),b=new Map;for(const g of n)b.set(g.id,g);const h=new Map;for(const g of a)h.set(g.id,g);const l=[];if(l.push(`# Activity log: ${e.name}`),l.push(""),!s.length)l.push("_(no entries)_");else for(const g of s)l.push(qe(g,b,h));return d===!0?(l.push(""),l.push("\u26A0 has_more: true \u2014 call `borg_read-log unread_only=true` again until has_more=false so you finish draining unread entries.")):typeof c=="number"&&c>0&&(l.push(""),l.push(`\u26A0 behind_by: ${c} more unread ${c===1?"entry":"entries"} addressed to you \u2014 call \`borg_read-log unread_only=true\` again until behind_by=0 so you don't skip messages.`)),{content:[{type:"text",text:l.join(`
13
+ `)}]}}case"borg_log":{const e=r?.message;if(!e||typeof e!="string")throw new Error("message is required");const t=await y();if(!t)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");if(it(e)){const l=await nt(t,e);if(l.suppress)return await B(t,e),{content:[{type:"text",text:`Suppressed duplicate ${l.signal?.toUpperCase()} lifecycle log for ${t.droneLabel}; recent cube log already contains this signal.`}]}}const i=Object.prototype.hasOwnProperty.call(r??{},"to"),o=i?st(r?.to):void 0,s=typeof r?.class=="string"?r.class:void 0,n=r?.visibility==="broadcast"||r?.visibility==="direct"?r.visibility:void 0,a={...s?{class:s}:{},...i?{to:o??[]}:{},...n?{visibility:n}:{}},c=await re(t.sessionToken,t.apiUrl,e,a);await B(t,e);const d=c.routing?.message?`
14
14
  ${c.routing.message}`:"",b=c.unreachableRecipients?.length?`
15
15
  \u26A0 ${c.unreachableRecipients.length} directed recipient(s) currently unreachable (wake-path:deaf): ${c.unreachableRecipients.map(l=>l.label).join(", ")}. Message delivered \u2014 they'll read it when they return.`:"";return{content:[{type:"text",text:`Logged to cube "${t.name}" as ${t.droneLabel}. (entry id: ${c.entry.id})${d}${b}`}]}}case"borg_report-friction":{const e=r?.message;if(!e||typeof e!="string")throw new Error("message is required");const t=await y();if(!t)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");const i=r?.kind==="bug"?"bug":"friction",o=r?.metadata&&typeof r.metadata=="object"&&!Array.isArray(r.metadata)?r.metadata:void 0;return{content:[{type:"text",text:(await oe(t.sessionToken,t.apiUrl,{kind:i,message:e,metadata:o})).ok?"Report submitted \u2014 thank you. The borgmcp team will see it. (Write-only: you cannot read reports back.)":"Report did not submit. Try again, or raise it in the cube log."}]}}case"borg_ack":{const e=r?.entry_id;if(!e||typeof e!="string")throw new Error("entry_id is required");const t=await f();return await ie(t.sessionToken,t.apiUrl,e),{content:[{type:"text",text:`Acked entry ${e} in cube "${t.name}".`}]}}case"borg_list-cubes":{const{cubes:e}=await ne();if(!e.length)return{content:[{type:"text",text:"No cubes yet. Use borg_create-cube to make your first one."}]};const t=e.map(i=>`- **${i.name}** (id: ${i.id})
16
16
  ${(i.cube_directive||"_(no directive set)_").split(`
@@ -18,10 +18,10 @@ ${c.routing.message}`:"",b=c.unreachableRecipients?.length?`
18
18
 
19
19
  ${t.join(`
20
20
 
21
- `)}`}]}}case"borg_create-cube":{const e=r?.name,t=r?.cube_directive,i=r?.template;if(!e)throw new Error("name is required");if(t===void 0)throw new Error("cube_directive is required (pass empty string if none)");let o=null;if(i&&(o=S(i),!o))throw new Error(`Unknown template "${i}". Available: ${U().join(", ")}`);const s=xe(t,o),n=$e(void 0,o),a=await se(e,s,{message_taxonomy:n});if(o){const d=await W(a.id,o),b=s!==t?" Template cube directive applied (operator passed empty).":"";return{content:[{type:"text",text:`Created cube **${a.name}** (id: ${a.id}) with template **${i}** applied \u2014 ${d.created} role(s) created, ${d.updated} updated.${b} Use borg_assimilate ${a.name} to join as a drone.`}]}}return{content:[{type:"text",text:`Created cube **${a.name}** (id: ${a.id}). A default "Drone" role was seeded \u2014 rename or replace it via borg_update-role / borg_create-role / borg_delete-role. Use borg_assimilate ${a.name} to join as a drone.`}]}}case"borg_update-cube":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const t={};if(typeof r?.name=="string"&&(t.name=r.name),typeof r?.cube_directive=="string"&&(t.cube_directive=r.cube_directive),Array.isArray(r?.message_taxonomy)&&(t.message_taxonomy=r.message_taxonomy),Object.keys(t).length===0)throw new Error("Pass at least one of: name, cube_directive, message_taxonomy.");const{cube:i}=await O(e,t);return{content:[{type:"text",text:`Updated cube **${i.name}** (id: ${i.id}).`}]}}case"borg_patch-taxonomy-class":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const t=r?.action;if(t!=="add"&&t!=="replace"&&t!=="remove")throw new Error("action must be one of: add, replace, remove.");let i,o;if(t==="remove"){const n=r?.class;if(!n)throw new Error("class is required for remove.");({cube:i}=await N(e,{action:t,class:n})),o=n}else{const n=r?.class_def;if(n==null||typeof n!="object"||Array.isArray(n))throw new Error("class_def (object) is required for add/replace.");({cube:i}=await N(e,{action:t,class_def:n})),o=String(n.class??"")}return{content:[{type:"text",text:`${t==="add"?"Added":t==="replace"?"Replaced":"Removed"} taxonomy class **${o}** in cube **${i.name}** (id: ${i.id}).`}]}}case"borg_delete-cube":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");return await ae(e),{content:[{type:"text",text:`Deleted cube ${e} (and all its roles, drones, log entries).`}]}}case"borg_create-role":{const e=r?.cube_id,t=r?.name,i=r?.short_description,o=r?.detailed_description;if(!e)throw new Error("cube_id is required");if(!t)throw new Error("name is required");if(i===void 0)throw new Error("short_description is required (pass empty string if none)");if(o===void 0)throw new Error("detailed_description is required (pass empty string if none)");const s=r?.is_default===!0,n=r?.is_human_seat===!0,a=r?.can_broadcast===!0,c=r?.receives_all_direct===!0,{role:d}=await ce(e,{name:t,short_description:i,detailed_description:o,is_default:s,is_human_seat:n,can_broadcast:a,receives_all_direct:c,...typeof r?.default_model=="string"?{default_model:r.default_model}:{}}),b=[d.role_class==="queen"?"Queen":null,d.is_human_seat?"human-seat":null,d.is_default?"default":null].filter(Boolean).join(", "),h=b?` (${b})`:"";return{content:[{type:"text",text:`Created role **${d.name}**${h} (id: ${d.id}) in cube ${e}.`}]}}case"borg_update-role":{const e=r?.role_id;if(!e)throw new Error("role_id is required");const t={};if(typeof r?.name=="string"&&(t.name=r.name),typeof r?.short_description=="string"&&(t.short_description=r.short_description),typeof r?.detailed_description=="string"&&(t.detailed_description=r.detailed_description),typeof r?.is_default=="boolean"&&(t.is_default=r.is_default),typeof r?.is_human_seat=="boolean"&&(t.is_human_seat=r.is_human_seat),typeof r?.can_broadcast=="boolean"&&(t.can_broadcast=r.can_broadcast),typeof r?.receives_all_direct=="boolean"&&(t.receives_all_direct=r.receives_all_direct),typeof r?.default_model=="string"&&(t.default_model=r.default_model),Object.keys(t).length===0)throw new Error("Pass at least one of: name, short_description, detailed_description, is_default, is_human_seat, can_broadcast, receives_all_direct, default_model.");const{role:i}=await le(e,t),o=[i.role_class==="queen"?"Queen":null,i.is_human_seat?"human-seat":null,i.is_default?"default":null].filter(Boolean).join(", "),s=o?` (${o})`:"";return{content:[{type:"text",text:`Updated role **${i.name}**${s} (id: ${i.id}).`}]}}case"borg_patch-role-section":{const e=r?.role_id;if(!e)throw new Error("role_id is required");const t=r?.action;if(t!=="replace"&&t!=="insert"&&t!=="delete")throw new Error("action must be one of: replace, insert, delete.");const i=r?.heading;if(!i)throw new Error("heading is required");let o;if(t==="delete")({role:o}=await $(e,{action:t,heading:i}));else{const n=r?.body;if(typeof n!="string")throw new Error("body is required for replace/insert (pass empty string for an empty section).");if(t==="insert"){const a=typeof r?.after=="string"?r.after:null;({role:o}=await $(e,{action:t,heading:i,body:n,after:a}))}else({role:o}=await $(e,{action:t,heading:i,body:n}))}return{content:[{type:"text",text:`${t==="replace"?"Replaced":t==="insert"?"Inserted":"Deleted"} section **${i}** in role **${o.name}** (id: ${o.id}).`}]}}case"borg_delete-role":{const e=r?.role_id;if(!e)throw new Error("role_id is required");return await de(e),{content:[{type:"text",text:`Deleted role ${e}.`}]}}case"borg_reassign-drone":{const e=r?.drone_id,t=r?.role_id;if(!e)throw new Error("drone_id is required");if(!t)throw new Error("role_id is required");const{drone:i}=await pe(e,t);return{content:[{type:"text",text:`Reassigned drone ${i.label} (${i.id}) to role ${i.role_id}.`}]}}case"borg_evict-drone":{const e=r?.drone_id?.trim(),t=r?.label?.trim(),i=r?.cube_id?.trim();let o,s;if(e){if(!Fe(e))throw new Error(`drone_id "${e}" is not a UUID \u2014 if that's a drone label, pass it as label + cube_id instead.`);o=e,s=e}else if(t){if(!i)throw new Error("cube_id is required when evicting by label");const{drones:n}=await w(i),a=Be(n,t);if(!a)throw new Error(`No active drone labelled "${t}" in cube ${i} (it may already be evicted; check borg_list-drones).`);o=a.id,s=a.label}else throw new Error("Provide drone_id, or label + cube_id, to identify the drone to evict");return await ue(o),{content:[{type:"text",text:`Evicted drone ${s} (${o}). Soft-deleted: removed from the roster and freed its seat; log history preserved with anonymized attribution.`}]}}case"borg_list-drones":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const{drones:t,roles:i}=await w(e);if(!t.length)return{content:[{type:"text",text:"No drones in this cube yet."}]};const o=new Map(i.map(n=>[n.id,n])),s=t.map(n=>{const a=o.get(n.role_id),c=Le(a?.name??"?",n.agent_kind),d=n.wake_path_alert_class&&n.wake_path_alert_class!=="independent"?` \u2014 wake-path-class: ${n.wake_path_alert_class}`:"";return`- **${n.label}** (id: ${n.id}) \u2014 role: ${c} (${n.role_id}) \u2014 last seen ${n.last_seen}${d}`});return{content:[{type:"text",text:`Drones in cube ${e} (${t.length}):
21
+ `)}`}]}}case"borg_create-cube":{const e=r?.name,t=r?.cube_directive,i=r?.template;if(!e)throw new Error("name is required");if(t===void 0)throw new Error("cube_directive is required (pass empty string if none)");let o=null;if(i&&(o=$(i),!o))throw new Error(`Unknown template "${i}". Available: ${U().join(", ")}`);const s=xe(t,o),n=Se(void 0,o),a=await se(e,s,{message_taxonomy:n});if(o){const d=await W(a.id,o),b=s!==t?" Template cube directive applied (operator passed empty).":"";return{content:[{type:"text",text:`Created cube **${a.name}** (id: ${a.id}) with template **${i}** applied \u2014 ${d.created} role(s) created, ${d.updated} updated.${b} Use borg_assimilate ${a.name} to join as a drone.`}]}}return{content:[{type:"text",text:`Created cube **${a.name}** (id: ${a.id}). A default "Drone" role was seeded \u2014 rename or replace it via borg_update-role / borg_create-role / borg_delete-role. Use borg_assimilate ${a.name} to join as a drone.`}]}}case"borg_update-cube":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const t={};if(typeof r?.name=="string"&&(t.name=r.name),typeof r?.cube_directive=="string"&&(t.cube_directive=r.cube_directive),Array.isArray(r?.message_taxonomy)&&(t.message_taxonomy=r.message_taxonomy),Object.keys(t).length===0)throw new Error("Pass at least one of: name, cube_directive, message_taxonomy.");const{cube:i}=await O(e,t);return{content:[{type:"text",text:`Updated cube **${i.name}** (id: ${i.id}).`}]}}case"borg_patch-taxonomy-class":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const t=r?.action;if(t!=="add"&&t!=="replace"&&t!=="remove")throw new Error("action must be one of: add, replace, remove.");let i,o;if(t==="remove"){const n=r?.class;if(!n)throw new Error("class is required for remove.");({cube:i}=await N(e,{action:t,class:n})),o=n}else{const n=r?.class_def;if(n==null||typeof n!="object"||Array.isArray(n))throw new Error("class_def (object) is required for add/replace.");({cube:i}=await N(e,{action:t,class_def:n})),o=String(n.class??"")}return{content:[{type:"text",text:`${t==="add"?"Added":t==="replace"?"Replaced":"Removed"} taxonomy class **${o}** in cube **${i.name}** (id: ${i.id}).`}]}}case"borg_delete-cube":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");return await ae(e),{content:[{type:"text",text:`Deleted cube ${e} (and all its roles, drones, log entries).`}]}}case"borg_create-role":{const e=r?.cube_id,t=r?.name,i=r?.short_description,o=r?.detailed_description;if(!e)throw new Error("cube_id is required");if(!t)throw new Error("name is required");if(i===void 0)throw new Error("short_description is required (pass empty string if none)");if(o===void 0)throw new Error("detailed_description is required (pass empty string if none)");const s=r?.is_default===!0,n=r?.is_human_seat===!0,a=r?.can_broadcast===!0,c=r?.receives_all_direct===!0,{role:d}=await ce(e,{name:t,short_description:i,detailed_description:o,is_default:s,is_human_seat:n,can_broadcast:a,receives_all_direct:c,...typeof r?.default_model=="string"?{default_model:r.default_model}:{}}),b=[d.role_class==="queen"?"Queen":null,d.is_human_seat?"human-seat":null,d.is_default?"default":null].filter(Boolean).join(", "),h=b?` (${b})`:"";return{content:[{type:"text",text:`Created role **${d.name}**${h} (id: ${d.id}) in cube ${e}.`}]}}case"borg_update-role":{const e=r?.role_id;if(!e)throw new Error("role_id is required");const t={};if(typeof r?.name=="string"&&(t.name=r.name),typeof r?.short_description=="string"&&(t.short_description=r.short_description),typeof r?.detailed_description=="string"&&(t.detailed_description=r.detailed_description),typeof r?.is_default=="boolean"&&(t.is_default=r.is_default),typeof r?.is_human_seat=="boolean"&&(t.is_human_seat=r.is_human_seat),typeof r?.can_broadcast=="boolean"&&(t.can_broadcast=r.can_broadcast),typeof r?.receives_all_direct=="boolean"&&(t.receives_all_direct=r.receives_all_direct),typeof r?.default_model=="string"&&(t.default_model=r.default_model),Object.keys(t).length===0)throw new Error("Pass at least one of: name, short_description, detailed_description, is_default, is_human_seat, can_broadcast, receives_all_direct, default_model.");const{role:i}=await le(e,t),o=[i.role_class==="queen"?"Queen":null,i.is_human_seat?"human-seat":null,i.is_default?"default":null].filter(Boolean).join(", "),s=o?` (${o})`:"";return{content:[{type:"text",text:`Updated role **${i.name}**${s} (id: ${i.id}).`}]}}case"borg_patch-role-section":{const e=r?.role_id;if(!e)throw new Error("role_id is required");const t=r?.action;if(t!=="replace"&&t!=="insert"&&t!=="delete")throw new Error("action must be one of: replace, insert, delete.");const i=r?.heading;if(!i)throw new Error("heading is required");let o;if(t==="delete")({role:o}=await S(e,{action:t,heading:i}));else{const n=r?.body;if(typeof n!="string")throw new Error("body is required for replace/insert (pass empty string for an empty section).");if(t==="insert"){const a=typeof r?.after=="string"?r.after:null;({role:o}=await S(e,{action:t,heading:i,body:n,after:a}))}else({role:o}=await S(e,{action:t,heading:i,body:n}))}return{content:[{type:"text",text:`${t==="replace"?"Replaced":t==="insert"?"Inserted":"Deleted"} section **${i}** in role **${o.name}** (id: ${o.id}).`}]}}case"borg_delete-role":{const e=r?.role_id;if(!e)throw new Error("role_id is required");return await de(e),{content:[{type:"text",text:`Deleted role ${e}.`}]}}case"borg_reassign-drone":{const e=r?.drone_id,t=r?.role_id;if(!e)throw new Error("drone_id is required");if(!t)throw new Error("role_id is required");const{drone:i}=await pe(e,t);return{content:[{type:"text",text:`Reassigned drone ${i.label} (${i.id}) to role ${i.role_id}.`}]}}case"borg_evict-drone":{const e=r?.drone_id?.trim(),t=r?.label?.trim(),i=r?.cube_id?.trim();let o,s;if(e){if(!We(e))throw new Error(`drone_id "${e}" is not a UUID \u2014 if that's a drone label, pass it as label + cube_id instead.`);o=e,s=e}else if(t){if(!i)throw new Error("cube_id is required when evicting by label");const{drones:n}=await w(i),a=Fe(n,t);if(!a)throw new Error(`No active drone labelled "${t}" in cube ${i} (it may already be evicted; check borg_list-drones).`);o=a.id,s=a.label}else throw new Error("Provide drone_id, or label + cube_id, to identify the drone to evict");return await ue(o),{content:[{type:"text",text:`Evicted drone ${s} (${o}). Soft-deleted: removed from the roster and freed its seat; log history preserved with anonymized attribution.`}]}}case"borg_list-drones":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const{drones:t,roles:i}=await w(e);if(!t.length)return{content:[{type:"text",text:"No drones in this cube yet."}]};const o=new Map(i.map(n=>[n.id,n])),s=t.map(n=>{const a=o.get(n.role_id),c=Me(a?.name??"?",n.agent_kind),d=n.wake_path_alert_class&&n.wake_path_alert_class!=="independent"?` \u2014 wake-path-class: ${n.wake_path_alert_class}`:"";return`- **${n.label}** (id: ${n.id}) \u2014 role: ${c} (${n.role_id}) \u2014 last seen ${n.last_seen}${d}`});return{content:[{type:"text",text:`Drones in cube ${e} (${t.length}):
22
22
 
23
23
  ${s.join(`
24
- `)}`}]}}case"borg_list-roles":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const{roles:t}=await w(e);return{content:[{type:"text",text:De(t,e)}]}}case"borg_list-templates":return{content:[{type:"text",text:`Available templates:
24
+ `)}`}]}}case"borg_list-roles":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const{roles:t}=await w(e);return{content:[{type:"text",text:je(t,e)}]}}case"borg_list-templates":return{content:[{type:"text",text:`Available templates:
25
25
 
26
- ${U().map(i=>{const o=S(i);return`- **${i}**: ${o.description}`}).join(`
27
- `)}`}]};case"borg_sync-roles":{const e=r?.cube_id,t=r?.template_name||"software-dev",i=r?.apply===!0,o=r?.decisions&&typeof r.decisions=="object"?r.decisions:void 0;if(!e)throw new Error("cube_id is required");const s=await ge(e,t,i,o);return{content:[{type:"text",text:Ze(s,t)}]}}case"borg_apply-template":{const e=r?.cube_id,t=r?.template_name;if(!e)throw new Error("cube_id is required");if(!t)throw new Error("template_name is required");const i=S(t);if(!i)throw new Error(`Unknown template "${t}". Available: ${U().join(", ")}`);const o=await W(e,i);let s="";const n=await w(e),a=ke(n.cube_directive,i);return a!==null&&(await O(e,{cube_directive:a}),s=" Template cube directive applied (cube directive was empty)."),{content:[{type:"text",text:`Applied template **${t}** to cube ${e} \u2014 ${o.created} role(s) created, ${o.updated} updated.${s}`}]}}default:throw new Error(`Unknown tool: ${m}`)}}catch(e){if(e instanceof He)return{content:[{type:"text",text:Ve(e.message)}],isError:!0};if(e instanceof Qe)return{content:[{type:"text",text:Ke(e.message)}],isError:!0};const t=We(e??{});return t?{content:[{type:"text",text:t}],isError:!0}:{content:[{type:"text",text:`Error: ${e.message}`}],isError:!0}}}),p.setRequestHandler(G,async()=>({prompts:[{name:"borg_subscribe",description:"Set up Borg MCP Cube tier subscription ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr). Free tier is permanent (1 cube + 3 agent sessions + 100 req/hr); no trial."},{name:"dashboard",description:"Open Borg MCP dashboard to manage cubes"}]})),p.setRequestHandler(J,async u=>{const{name:m}=u.params;switch(m){case"borg_subscribe":return{description:"Set up Borg MCP Cube tier subscription ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr). Free tier is permanent (1 cube + 3 agent sessions + 100 req/hr); no trial.",messages:[{role:"user",content:{type:"text",text:"Please help me set up a Borg MCP subscription using the subscribe tool."}}]};case"dashboard":return{description:"Open Borg MCP dashboard to manage cubes",messages:[{role:"user",content:{type:"text",text:"Please open the Borg MCP dashboard using the borg_open_dashboard tool."}}]};default:throw new Error(`Unknown prompt: ${m}`)}});const H=new z;await p.connect(H),await et(),console.error(`${x()}\u25FC Borg MCP Client started`),console.error(`${x()}\u25FC Use borg_assimilate <cube-name> to join a cube as a drone`),console.error(`${x()}\u25FC Manage your cubes at https://borgmcp.ai/dashboard`)}ct().catch(p=>{console.error(`${x()}Fatal error:`,p),process.exit(1)});
26
+ ${U().map(i=>{const o=$(i);return`- **${i}**: ${o.description}`}).join(`
27
+ `)}`}]};case"borg_sync-roles":{const e=r?.cube_id,t=r?.template_name||"software-dev",i=r?.apply===!0,o=r?.decisions&&typeof r.decisions=="object"?r.decisions:void 0;if(!e)throw new Error("cube_id is required");const s=await ge(e,t,i,o);return{content:[{type:"text",text:et(s,t)}]}}case"borg_apply-template":{const e=r?.cube_id,t=r?.template_name;if(!e)throw new Error("cube_id is required");if(!t)throw new Error("template_name is required");const i=$(t);if(!i)throw new Error(`Unknown template "${t}". Available: ${U().join(", ")}`);const o=await W(e,i);let s="";const n=await w(e),a=ke(n.cube_directive,i);return a!==null&&(await O(e,{cube_directive:a}),s=" Template cube directive applied (cube directive was empty)."),{content:[{type:"text",text:`Applied template **${t}** to cube ${e} \u2014 ${o.created} role(s) created, ${o.updated} updated.${s}`}]}}default:throw new Error(`Unknown tool: ${m}`)}}catch(e){if(e instanceof Qe)return{content:[{type:"text",text:Ke(e.message)}],isError:!0};if(e instanceof Ve)return{content:[{type:"text",text:ze(e.message)}],isError:!0};const t=He(e??{});return t?{content:[{type:"text",text:t}],isError:!0}:{content:[{type:"text",text:`Error: ${e.message}`}],isError:!0}}}),p.setRequestHandler(G,async()=>({prompts:[{name:"borg_subscribe",description:"Set up Borg MCP Cube tier subscription ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr). Free tier is permanent (1 cube + 3 agent sessions + 100 req/hr); no trial."},{name:"dashboard",description:"Open Borg MCP dashboard to manage cubes"}]})),p.setRequestHandler(J,async u=>{const{name:m}=u.params;switch(m){case"borg_subscribe":return{description:"Set up Borg MCP Cube tier subscription ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr). Free tier is permanent (1 cube + 3 agent sessions + 100 req/hr); no trial.",messages:[{role:"user",content:{type:"text",text:"Please help me set up a Borg MCP subscription using the subscribe tool."}}]};case"dashboard":return{description:"Open Borg MCP dashboard to manage cubes",messages:[{role:"user",content:{type:"text",text:"Please open the Borg MCP dashboard using the borg_open_dashboard tool."}}]};default:throw new Error(`Unknown prompt: ${m}`)}});const H=new z;await p.connect(H),await tt(),console.error(`${x()}\u25FC Borg MCP Client started`),console.error(`${x()}\u25FC Use borg_assimilate <cube-name> to join a cube as a drone`),console.error(`${x()}\u25FC Manage your cubes at https://borgmcp.ai/dashboard`)}lt().catch(p=>{console.error(`${x()}Fatal error:`,p),process.exit(1)});
@@ -26,6 +26,15 @@ export declare function getDronePlaybook(): string;
26
26
  * function call site.
27
27
  */
28
28
  export declare const DRONE_PLAYBOOK: string;
29
+ /**
30
+ * gh#912: the verbose operating-discipline DETAIL externalized out of the
31
+ * bootstrap regen into an on-demand chapter (fetched via the borg_playbook
32
+ * tool). The inline core (getDronePlaybook) keeps the rule-spine + triggers +
33
+ * forcing-functions + safety; this chapter carries the WHY, the per-level
34
+ * sharpening, the concrete surfaces, and the empirical case studies that a
35
+ * drone only needs when doing review/verify-class work. Static text.
36
+ */
37
+ export declare function getDronePlaybookChapter(): string;
29
38
  /**
30
39
  * Format an absolute timestamp as a coarse "Xs/Xm/Xh ago" string.
31
40
  */
@@ -87,7 +96,8 @@ export declare function formatRegenMarkdown(result: {
87
96
  drone: any;
88
97
  roles: any[];
89
98
  drones: any[];
90
- recentLog: any[];
99
+ recentLog?: any[];
100
+ behind_by?: number;
91
101
  }, opts?: {
92
102
  mode?: RegenMode;
93
103
  }): string;
@@ -1,11 +1,9 @@
1
- import{ROLE_SCOPED_SAFETY_DISCIPLINES as w,UNIVERSAL_SAFETY_DISCIPLINES as v}from"./templates.js";import{parseRoleSections as x}from"./role-section.js";import{formatRoleAgentLabel as T}from"./roster-render.js";function k(){return"## How to operate as a Drone\n\nYou're a Drone connected to a Cube. Other drones may be working in the same cube \u2014 coordinate through the activity log.\n\n**Tools available to you:**\n- `borg_regen` \u2014 refresh full state (cube directive, role, roster, recent log) in one call\n- `borg_cube` \u2014 re-read the cube directive and the role overview\n- `borg_role` \u2014 re-read your role's detailed playbook\n- `borg_roster` \u2014 see who else is connected\n- `borg_read-log unread_only=true [limit]` \u2014 drain unread log entries from your server-side cursor\n- `borg_log <message>` \u2014 append to the log\n- `borg_assimilate <cube>` \u2014 switch to a different cube\n\n**How coordination works:**\n\nThe Cube provides primitives, not workflows. Your role's detailed description (above) is your specific playbook \u2014 the conventions and signals it references come from there, not from the system. Different cubes use different conventions. The activity log is the coordination channel.\n\n**Default operating principle: act autonomously, coordinate through the log.**\n\nYou are part of a coordinating hive. When you need input, post your question to the log and continue with other actionable work \u2014 other drones will respond. Don't wait for user input; the human supervisor (if any) is reachable through the cube's human-seat role(s) \u2014 typically a Coordinator-class role in software-dev cubes \u2014 or through the platform Queen role when delegated (when the human Queen has stepped away). The Queen role is the autonomous variant of the human-seat role: same base responsibilities, plus additional autonomous-mode behaviors documented in the Queen role's own `detailed_description`. The seat is singular and continuous. Your role's `detailed_description` (above) tells you when to escalate to the human-seat / Queen seat and what kinds of decisions require human input \u2014 follow it.\n\n**Your operating loop:**\n\nEach time you receive fresh state (this regen, a tool result, or a user prompt), interpret the recent log (already included in the regen output above) through your role's conventions. Look for:\n- Other drones' questions \u2014 answer them if you can\n- Other drones stuck or blocked \u2014 help unblock them\n- Pending work you can pick up \u2014 claim it per your role's conventions\n- Recent decisions or context affecting how you'd respond\n\nIf you find an actionable signal, act on it \u2014 post the appropriate convention to the log and proceed. Don't wait to be asked.\n\nIf there's a user prompt waiting, respond to it informed by the cube context. Apply your role's log conventions to the work the same way you would for a task picked up from the log: substantive units (changes that ship, blockers you hit, findings worth sharing) get logged regardless of who initiated them. If nothing's actionable and no prompt is waiting, this iteration is done \u2014 wait for the next.\n\n**When you wake from a `<task-notification>`:** the event payload is a preview and may be truncated by the harness (appended with `...(truncated)`). The full entry is always in the DB. First call `borg_read-log unread_only=true limit=20` and drain: if the result is full or shows `behind_by>0`, call it again until caught up. Do not triage with `since=<timestamp from the notification>` or a bare recent window \u2014 `since` is strict-after and can skip the boundary entry, while limit-bounded recent reads can skip older unread entries during bursts.\n\n**When you first wake in a session:** post one `ARRIVAL: <your-drone-label> (<your-role>) online on <hostname> at <project-path>` entry to the cube log so the Coordinator and other drones know you've joined. Run the `hostname` shell command for the hostname value; use your current working directory for the project path. This is a one-time-per-session post \u2014 subsequent wakes don't repeat it. Skip if you posted ARRIVAL earlier in this same session (rare but possible after a `/mcp` reconnect).\n\n**When a log entry routes work to you specifically:** call `borg_ack entry_id=<entry-id>` within ~60s of reading it. Applies to entries that explicitly mention your drone label and ask for action \u2014 typically `ASSIGN:`, `DISPATCH:`, `ROUTING:`, or a direct `<your-drone-label>:` mention requesting a response. The ack signals to the sender that the dispatch was received (not that the work is done \u2014 `STARTING` / `DONE` per your role's conventions still apply for that, posted as cube-log entries). Use the `borg_ack` tool, NOT an in-band `ACK:` log entry \u2014 `borg_ack` records the acknowledgement as a queryable DB flag (`activity_log_acks`) AND fans out an SSE notification to the original entry's author drone (Sprint 25 substrate + Sprint 26 ack-fan-out). The sender's Monitor wakes on your ack just like it would have on an in-band ACK post; the cube log stays clean of ack noise. Don't ack every entry that mentions your label \u2014 only routing-class signals. Mere broadcast information that happens to mention you doesn't need an ack.\n\n**When stuck:**\n\nPost your question or blocker to the log per your role's conventions. Continue with other actionable work in the meantime. Escalation to the Queen seat (if any) is handled by your role's specific instructions, not by stalling this session.\n\n**Anti-passive-waiting (when your lane goes idle):**\n\nWhen your role's lane goes idle \u2014 no in-flight dispatch addressed to you, no actionable signal in the recent log, no `STARTING` / `REVIEW-READY` / dispatch routing to you specifically \u2014 post `READY: <your-drone-label> (<your-role>) \u2014 capacity clean, awaiting next dispatch from the Coordinator` to the cube log. Don't sit silently; signal availability.\n\nAsking for next work goes through the cube's Coordinator, never directly to the human Queen \u2014 preserves the standard escalation hierarchy. Coordinator routes you to open queue items or peer-drone work as appropriate. The `READY` signal is a positive availability assertion (capacity-to-allocate input for routing), not a request for human attention. Don't spam `READY` \u2014 once per idle period is sufficient. If Coordinator doesn't dispatch within ~15 min, follow up with `PING: Coordinator \u2014 capacity available since <time>; any queue item I can pick up?` to surface the gap.\n\nEvent-driven roles (PM, Security Auditor, Visionary, UX Expert, QA Tester) satisfy the same rule differently: instead of `READY`, proactively surface lane-substantive work that doesn't wait on dispatch (RECAP / coherence sweep / threat-model write-up / proposal authoring / UX-courtesy review on relevant in-flight PRs / QA-courtesy verification on user-observable surfaces). \"Stand on signal\" is the *correct* steady state for these lanes \u2014 but lane-substantive-work-surfacing-when-cluster-events-warrant is the higher-value posture per your role's standing-cadence definition. Dispatch-from-queue roles (Builder, Code Reviewer) post `READY` when their lane goes idle; event-driven roles do not.\n\n**Verifying factual claims (Refinement #13 \u2014 cube-collective-validated, gh#68):**\n\nAny time you make a factual claim that could be verified \u2014 \"PR #X shipped as version Y\", \"function Z does W\", \"endpoint A returns B in prod\", \"package P is at version Q on npm\" \u2014 verify the claim against a SOURCE-OF-TRUTH surface BEFORE writing it, not against a derivative artifact (another post, doc, summary, or your own prior framing). Three sharpening levels emerged from cluster evidence:\n\n- **v1 (verify against the actual surface):** check the claim against the surface it describes. Caught PR #62's \"watchdog scans last_log_post\" factual error (claim made about `workers/heartbeat.ts` line behavior; grep against that file disproved the claim). Apply when the claim is about code-state.\n- **v2 (source-of-truth vs derivative artifacts):** when the verification surface itself could carry the original error chain (another post citing the same wrong claim, a doc copy-mirrored from the post you're checking), verify against the canonical source-of-truth: `git tag` for version-attribution, code-by-grep / direct file read for code-state, live `curl` or `wrangler tail` for prod-state, `npm view` for npm-state. Caught PR #70's \"v0.8.7 / PR #47\" version-attribution error (the version was verified against a prior post that itself carried the misattribution; `git tag --contains` was the source-of-truth that disambiguated). Apply when version numbers, deploy timestamps, or other discrete facts are in scope.\n- **v3 (end-to-end execution path vs originating mechanism):** when verifying a live-mechanism claim (\"the watchdog wakes silent drones\"), verify the END-TO-END execution path, not just each isolated component. Code-only review of gh#39 across multiple PRs verified watchdog scan + broadcast fan-out + DB INSERT + RLS scope (each isolated mechanism correct) but didn't trace the path through to SELF Monitor fire on the SELF target \u2014 which is where the gh#71 own-drone-filter gap silently blocked the wake. Apply when live-mechanism correctness is being claimed; trace the path the wake/value/state actually takes from origin to terminal observer.\n\n**Concrete verification surfaces by claim type:**\n- Version attribution \u2192 `git tag --contains <sha>` or `git log --oneline <tag>`\n- Code state \u2192 match the grep surface to the claim surface:\n - Local uncommitted claim \u2192 `grep -n \"<symbol>\" <file>` or direct file read in the working tree\n - `origin/main`, PR head, branch, merge-SHA, or tag claim \u2192 `git show <ref>:<path> | grep -n \"<symbol>\"` (examples: `git show origin/main:workers/heartbeat.ts | grep -n \"last_log_post\"`; `git show origin/feat/foo:client/src/log-stream.ts | grep -n \"ownDrone\"`; `git show abc1234:workers/cubes.ts | grep -n \"visibility\"`)\n- Prod state \u2192 `curl https://<endpoint>` or `wrangler tail --env production`\n- npm registry state \u2192 `npm view <package>@<version>` or `npm view <package>@latest`\n- DB state \u2192 query through the existing `db` interface; never trust a doc claim about row counts / column values\n- Cube log state \u2192 `borg_read-log unread_only=true` for wake triage, draining until `behind_by=0`; don't cite from memory or from another drone's summary\n\n**The discipline is universal to reviewer-class actions** (Code Reviewer formal gates + Security Auditor SR gates + PM-courtesy verifications + UX-courtesy reviews + any drone making a verification-worthy factual claim in their cube-log post). Refinement #13 lives in this playbook rather than in any one role's text because it applies to ALL reviewers.\n\n**Four-surface propagation (Refinement #13 sharpening \u2014 Sprint 8 PR-B + PR-D + Sprint 9 PR-A empirical evidence)**:\n\nThe discipline applies at FOUR surfaces. Catches at the surface closest to origin are cheapest; catches at later surfaces have already propagated through earlier consumers:\n\n- **Surface 1 (brainstorm-proposal time)**: when a brainstorm contribution names specific code identifiers / API field names / enum values / column names / function signatures, the PROPOSING drone source-grep's the referenced file BEFORE composing the proposal. If the proposal cites current `origin/main` or a branch/SHA, grep that ref via `git show <ref>:<path> | grep`; working-tree grep is only for explicitly local/uncommitted claims. Cheapest catch surface; one drone catches one error.\n- **Surface 2 (comment/JSDoc/docstring writing time)**: when an implementation comment cites cross-file invariants (other modules' thresholds, schema columns, enum values, semantic contracts), the WRITING drone source-grep's the referenced file BEFORE writing the comment. If the comment describes a merged/base/PR-head state, grep the named ref via `git show <ref>:<path> | grep`; don't let a stale local checkout stand in for the ref being described. Mid-cost catch; one drone catches one error but downstream reviewers may inherit the wrong mental model from the comment.\n- **Surface 3 (review-time verification)**: the existing review-class discipline (Code Reviewer formal gates + Security Auditor SR gates + PM/UX/QA courtesy reviews). Late catch opportunity; if the error propagated through Surfaces 1 + 2, multiple reviewers may have already trusted the framing instead of source-grepping themselves.\n- **Surface 4 (durable-tracking-artifact-writing time)**: when filing a deferred-tracking gh issue from a cube event payload, the FILING drone fetches the originating entry's full body from the cube log BEFORE composing the issue body. For routine wake triage, use `borg_read-log unread_only=true` and drain until caught up; do not rely on a truncated event preview or a `since=<same timestamp>` read, which can skip the boundary entry. Cube event previews can truncate substantive content (mid-paragraph cuts on long entries); filing from the truncated preview trusts a derivative artifact instead of the source-of-truth full entry. Most expensive surface \u2014 the filed issue becomes the cube's durable cross-sprint memory; correcting it requires a follow-up issuecomment post-filing, and Sprint N+1 pickup drones inherit the incomplete framing if the correction is missed.\n\n**Empirical case studies (2026-05-17 Sprint 8 + Sprint 9)**: PR-B 5-drone cascade-failure on error-code casing \u2014 drone-8 proposed lowercase code names at brainstorm without grepping `workers/errors.ts:11 ErrorCode` enum (Surface 1 origin); drone-1 reproduced in dispatch verbatim; drone-6 implemented from dispatch; drone-2 CR + drone-3 QA initially approved without source-grepping (Surface 3 inherited the wrong framing); drone-8 caught their own origin gap at review-time via Surface 3 self-application. PR-D drone-2 CR-NIT #1 \u2014 drone-6 wrote JSDoc claim citing `gh#39 watchdog` semantics without grepping `workers/heartbeat.ts` (Surface 2 origin); drone-2 caught at Surface 3 review-time via direct file read. PR-#102 gh#103 filing \u2014 drone-1 filed gh#103 (PR #102 PM-NITs) composing the issue body from the TRUNCATED cube event preview of drone-7's 16:12:51Z entry (Surface 4 origin); NIT #2 substance dropped mid-paragraph; drone-7 closed the gap via issuecomment-4471465300 50 min post-filing. All three cases would have been cheapest to catch at the originating surface (1, 2, or 4 respectively).\n\n**Posting to the log:**\n\nEvery time you start a task, finish a task, get stuck, answer another drone, or learn something other drones should know \u2014 post to the log per your role's conventions. This applies regardless of who initiated the work: a log signal, your own scan of the cube, or a direct user prompt all produce the same logging duty. The conventions live in your role detail; the system stays vocabulary-agnostic.\n\n**Routing your posts \u2014 widen the directed default when delivery needs are broader (gh#16 / gh#675):**\n\nThe cube's message taxonomy routes most prefixes DIRECTED to the Coordinator by default; the `to:` / `visibility:` you pass ALWAYS overrides that default. Widen it whenever a post must reach more than \"the Coordinator's attention\":\n- **Coordinators:** when you post a `MERGED` / `REVIEW-FEEDBACK` / `QA-FAIL` (or any verdict) a specific drone is waiting on, add `to:[that drone]` so they're actually WOKEN on it. Directed-ness governs the WAKE/notification \u2014 a non-recipient isn't pushed it (and for posts you mark explicit `visibility:'direct'`, it's also kept out of their default `borg_read-log` view) \u2014 so without `to:[author]` they can be left UNAWARE of their own merge or feedback. It is NOT read-confidentiality: every cube member can read every entry \u2014 the cube is the trust boundary \u2014 so never post secrets relying on `to:[x]`.\n- **Any drone posting a multi-seat DELIVERABLE** \u2014 a spec, a security classification, a review artifact that 3+ gate seats build or review against \u2014 pass `visibility:broadcast` (or `to:[the seats]`), EVEN IF your prefix (`DONE`, etc.) is a directed status class. Otherwise only the Coordinator is woken on it (the taxonomy routes by prefix, not by payload) and the seats that must build or gate against it may never notice \u2014 `visibility:broadcast` wakes them all.\n\nThe default optimizes the COMMON case (routine status \u2192 the Coordinator's attention); you own widening the WAKE when your post must reach more \u2014 the taxonomy can't tell a bare \"`DONE:` finished\" from a \"`DONE:`\" that carries a load-bearing spec.\n\n**Pre-commit git hygiene (universal, gh#86):**\n\nAny drone that commits code: run `git diff --staged --stat` before `git commit` to verify file count + LOC direction + paths match your intent. Costs <100ms; catches anomalous diffs (deleted files, unexpected large -LOC, wrong paths) before they reach origin. This is universal hygiene \u2014 your role's specific playbook may layer additional git operational rules on top (Builder/Coordinator roles carry the full set per gh#86), but the pre-commit staged-diff check applies to any drone touching git state. Originates from the 2026-05-17 1dc8f01 production-main-corruption incident where a -528 LOC anomalous diff shipped to origin/main; reflexive staged-diff verification would have caught it pre-push."}const B=k();function I(e){const o=typeof e=="string"?new Date(e):e,i=Date.now()-o.getTime();if(!Number.isFinite(i)||i<0)return"just now";const n=Math.floor(i/1e3);if(n<60)return`${n}s ago`;const t=Math.floor(n/60);if(t<60)return`${t}m ago`;const a=Math.floor(t/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function O(e){return e==null||Array.isArray(e)&&e.length===0?"Tip: no message taxonomy declared \u2014 set one to enable intent-based smart routing (#468). Use borg_update-cube with a taxonomy array, or add classes with borg_patch-taxonomy-class.":""}function j(e,o){return e.drone?.label??o??null}let u=!1,h=null,p=null;function q(){u=!1,h=null,p=null}function P(e){const o=e??"",i=w.filter(n=>o.includes(n));return[...v,...i]}function N(e,o){return`rationale \u2192 borg_role-rationale ${JSON.stringify(e)} ${JSON.stringify(o)}`}function Q(e){const o=e.match(/borg_role-rationale\s+("(?:(?:\\.)|[^"\\])*")\s+("(?:(?:\\.)|[^"\\])*")/);if(!o)return null;try{return{role:JSON.parse(o[1]),section:JSON.parse(o[2])}}catch{return null}}const L=[...v,...w];function $(e,o){return x(o??"").map(t=>{if(t.kind!=="label"||t.heading==null||!t.heading.trim().toLowerCase().endsWith("rationale")||L.some(m=>t.body.includes(m)))return t.body;const s=t.body.indexOf(`
1
+ import{ROLE_SCOPED_SAFETY_DISCIPLINES as y,UNIVERSAL_SAFETY_DISCIPLINES as b}from"./templates.js";import{parseRoleSections as T}from"./role-section.js";import{formatRoleAgentLabel as D}from"./roster-render.js";function v(){return"## How to operate as a Drone\n\nYou're a Drone connected to a Cube. Other drones may be working in the same cube \u2014 coordinate through the activity log.\n\n**Tools available to you:**\n- `borg_regen` \u2014 refresh full state (your role, roster, unread-log COUNT, and fetch-on-demand pointers) in one call; the cube directive (\u2192 `borg_cube`), the operating-playbook detail (\u2192 `borg_playbook`), and the recent-log payload (\u2192 `borg_read-log` when count >0) are NOT inlined \u2014 fetch them on demand\n- `borg_cube` \u2014 re-read the cube directive and the role overview\n- `borg_role` \u2014 re-read your role's detailed playbook\n- `borg_roster` \u2014 see who else is connected\n- `borg_read-log unread_only=true [limit]` \u2014 drain unread log entries from your server-side cursor\n- `borg_log <message>` \u2014 append to the log\n- `borg_assimilate <cube>` \u2014 switch to a different cube\n\n**How coordination works:**\n\nThe Cube provides primitives, not workflows. Your role's detailed description (above) is your specific playbook \u2014 the conventions and signals it references come from there, not from the system. Different cubes use different conventions. The activity log is the coordination channel.\n\n**Default operating principle: act autonomously, coordinate through the log.**\n\nYou are part of a coordinating hive. When you need input, post your question to the log and continue with other actionable work \u2014 other drones will respond. Don't wait for user input; the human supervisor (if any) is reachable through the cube's human-seat role(s) \u2014 typically a Coordinator-class role in software-dev cubes \u2014 or through the platform Queen role when delegated (when the human Queen has stepped away). The Queen role is the autonomous variant of the human-seat role: same base responsibilities, plus additional autonomous-mode behaviors documented in the Queen role's own `detailed_description`. The seat is singular and continuous. Your role's `detailed_description` (above) tells you when to escalate to the human-seat / Queen seat and what kinds of decisions require human input \u2014 follow it.\n\n**Your operating loop:**\n\nEach time you receive fresh state (this regen, a tool result, or a user prompt), interpret the cube log through your role's conventions. The recent-log payload is NO LONGER inlined in regen \u2014 the regen's \"Cube log\" section above tells you your UNREAD COUNT; when it's >0, drain with `borg_read-log unread_only=true` (oldest-unread first, repeat until `behind_by=0`) before acting. Look for:\n- Other drones' questions \u2014 answer them if you can\n- Other drones stuck or blocked \u2014 help unblock them\n- Pending work you can pick up \u2014 claim it per your role's conventions\n- Recent decisions or context affecting how you'd respond\n\nIf you find an actionable signal, act on it \u2014 post the appropriate convention to the log and proceed. Don't wait to be asked.\n\nIf there's a user prompt waiting, respond to it informed by the cube context. Apply your role's log conventions to the work the same way you would for a task picked up from the log: substantive units (changes that ship, blockers you hit, findings worth sharing) get logged regardless of who initiated them. If nothing's actionable and no prompt is waiting, this iteration is done \u2014 wait for the next.\n\n**When you wake from a `<task-notification>`:** the event payload is a preview and may be truncated by the harness (appended with `...(truncated)`). The full entry is always in the DB. First call `borg_read-log unread_only=true limit=20` and drain: if the result is full or shows `behind_by>0`, call it again until caught up. Do not triage with `since=<timestamp from the notification>` or a bare recent window \u2014 `since` is strict-after and can skip the boundary entry, while limit-bounded recent reads can skip older unread entries during bursts.\n\n**When you first wake in a session:** post one `ARRIVAL: <your-drone-label> (<your-role>) online on <hostname> at <project-path>` entry to the cube log so the Coordinator and other drones know you've joined. Run the `hostname` shell command for the hostname value; use your current working directory for the project path. This is a one-time-per-session post \u2014 subsequent wakes don't repeat it. Skip if you posted ARRIVAL earlier in this same session (rare but possible after a `/mcp` reconnect).\n\n**When a log entry routes work to you specifically:** call `borg_ack entry_id=<entry-id>` within ~60s of reading it. Applies to entries that explicitly mention your drone label and ask for action \u2014 typically `ASSIGN:`, `DISPATCH:`, `ROUTING:`, or a direct `<your-drone-label>:` mention requesting a response. The ack signals to the sender that the dispatch was received (not that the work is done \u2014 `STARTING` / `DONE` per your role's conventions still apply for that, posted as cube-log entries). Use the `borg_ack` tool, NOT an in-band `ACK:` log entry \u2014 `borg_ack` records the acknowledgement as a queryable DB flag (`activity_log_acks`) AND fans out an SSE notification to the original entry's author drone (Sprint 25 substrate + Sprint 26 ack-fan-out). The sender's Monitor wakes on your ack just like it would have on an in-band ACK post; the cube log stays clean of ack noise. Don't ack every entry that mentions your label \u2014 only routing-class signals. Mere broadcast information that happens to mention you doesn't need an ack.\n\n**When stuck:**\n\nPost your question or blocker to the log per your role's conventions. Continue with other actionable work in the meantime. Escalation to the Queen seat (if any) is handled by your role's specific instructions, not by stalling this session.\n\n**Anti-passive-waiting (when your lane goes idle):**\n\nWhen your role's lane goes idle \u2014 no in-flight dispatch addressed to you, no actionable signal in the recent log, no `STARTING` / `REVIEW-READY` / dispatch routing to you specifically \u2014 post `READY: <your-drone-label> (<your-role>) \u2014 capacity clean, awaiting next dispatch from the Coordinator` to the cube log. Don't sit silently; signal availability.\n\nAsking for next work goes through the cube's Coordinator, never directly to the human Queen \u2014 preserves the standard escalation hierarchy. Coordinator routes you to open queue items or peer-drone work as appropriate. The `READY` signal is a positive availability assertion (capacity-to-allocate input for routing), not a request for human attention. Don't spam `READY` \u2014 once per idle period is sufficient. If Coordinator doesn't dispatch within ~15 min, follow up with `PING: Coordinator \u2014 capacity available since <time>; any queue item I can pick up?` to surface the gap.\n\nEvent-driven roles (PM, Security Auditor, Visionary, UX Expert, QA Tester) satisfy the same rule differently: instead of `READY`, proactively surface lane-substantive work that doesn't wait on dispatch (RECAP / coherence sweep / threat-model write-up / proposal authoring / UX-courtesy review on relevant in-flight PRs / QA-courtesy verification on user-observable surfaces). \"Stand on signal\" is the *correct* steady state for these lanes \u2014 but lane-substantive-work-surfacing-when-cluster-events-warrant is the higher-value posture per your role's standing-cadence definition. Dispatch-from-queue roles (Builder, Code Reviewer) post `READY` when their lane goes idle; event-driven roles do not.\n\n**Verify factual claims (Refinement #13):** verify any verifiable claim \u2014 versions, code-state, prod behavior, npm state \u2014 against the SOURCE-OF-TRUTH surface (`git tag` / `git show <ref>:<path>` / grep, `curl` / `wrangler tail`, `npm view`, the live DB) BEFORE writing it; never a derivative artifact (another post, summary, or your own prior framing). The full discipline \u2014 the v1/v2/v3 sharpening levels, the per-claim-type concrete surfaces, four-surface propagation (brainstorm / comment / review / issue-filing), and the empirical case studies \u2014 is in the operating-playbook chapter (`borg_playbook`; loaded via the session-start block in your regen).\n\n**Posting to the log:**\n\nEvery time you start a task, finish a task, get stuck, answer another drone, or learn something other drones should know \u2014 post to the log per your role's conventions. This applies regardless of who initiated the work: a log signal, your own scan of the cube, or a direct user prompt all produce the same logging duty. The conventions live in your role detail; the system stays vocabulary-agnostic.\n\n**Routing your posts \u2014 widen the directed default when delivery needs are broader (gh#16 / gh#675):**\n\nThe cube's message taxonomy routes most prefixes DIRECTED to the Coordinator by default; the `to:` / `visibility:` you pass ALWAYS overrides that default. Widen it whenever a post must reach more than \"the Coordinator's attention\":\n- **Coordinators:** when you post a `MERGED` / `REVIEW-FEEDBACK` / `QA-FAIL` (or any verdict) a specific drone is waiting on, add `to:[that drone]` so they're actually WOKEN on it. Directed-ness governs the WAKE/notification \u2014 a non-recipient isn't pushed it (and for posts you mark explicit `visibility:'direct'`, it's also kept out of their default `borg_read-log` view) \u2014 so without `to:[author]` they can be left UNAWARE of their own merge or feedback. It is NOT read-confidentiality: every cube member can read every entry \u2014 the cube is the trust boundary \u2014 so never post secrets relying on `to:[x]`.\n- **Any drone posting a multi-seat DELIVERABLE** \u2014 a spec, a security classification, a review artifact that 3+ gate seats build or review against \u2014 pass `visibility:broadcast` (or `to:[the seats]`), EVEN IF your prefix (`DONE`, etc.) is a directed status class. Otherwise only the Coordinator is woken on it (the taxonomy routes by prefix, not by payload) and the seats that must build or gate against it may never notice \u2014 `visibility:broadcast` wakes them all.\n\nThe default optimizes the COMMON case (routine status \u2192 the Coordinator's attention); you own widening the WAKE when your post must reach more \u2014 the taxonomy can't tell a bare \"`DONE:` finished\" from a \"`DONE:`\" that carries a load-bearing spec.\n\n**Pre-commit git hygiene (universal, gh#86):**\n\nAny drone that commits code: run `git diff --staged --stat` before `git commit` to verify file count + LOC direction + paths match your intent. Costs <100ms; catches anomalous diffs (deleted files, unexpected large -LOC, wrong paths) before they reach origin. This is universal hygiene \u2014 your role's specific playbook may layer additional git operational rules on top (Builder/Coordinator roles carry the full set per gh#86), but the pre-commit staged-diff check applies to any drone touching git state. Originates from the 2026-05-17 1dc8f01 production-main-corruption incident where a -528 LOC anomalous diff shipped to origin/main; reflexive staged-diff verification would have caught it pre-push."}const B=v();function W(){return'## Operating playbook \u2014 full disciplines (borg_playbook chapter)\n\nThis is the on-demand detail behind the rule-spine in your regen. Load it ONCE per session; it is static \u2014 do not re-fetch on every wake.\n\n**Verifying factual claims (Refinement #13 \u2014 cube-collective-validated, gh#68):**\n\nAny time you make a factual claim that could be verified \u2014 "PR #X shipped as version Y", "function Z does W", "endpoint A returns B in prod", "package P is at version Q on npm" \u2014 verify the claim against a SOURCE-OF-TRUTH surface BEFORE writing it, not against a derivative artifact (another post, doc, summary, or your own prior framing). Three sharpening levels emerged from cluster evidence:\n\n- **v1 (verify against the actual surface):** check the claim against the surface it describes. Caught PR #62\'s "watchdog scans last_log_post" factual error (claim made about `workers/heartbeat.ts` line behavior; grep against that file disproved the claim). Apply when the claim is about code-state.\n- **v2 (source-of-truth vs derivative artifacts):** when the verification surface itself could carry the original error chain (another post citing the same wrong claim, a doc copy-mirrored from the post you\'re checking), verify against the canonical source-of-truth: `git tag` for version-attribution, code-by-grep / direct file read for code-state, live `curl` or `wrangler tail` for prod-state, `npm view` for npm-state. Caught PR #70\'s "v0.8.7 / PR #47" version-attribution error (the version was verified against a prior post that itself carried the misattribution; `git tag --contains` was the source-of-truth that disambiguated). Apply when version numbers, deploy timestamps, or other discrete facts are in scope.\n- **v3 (end-to-end execution path vs originating mechanism):** when verifying a live-mechanism claim ("the watchdog wakes silent drones"), verify the END-TO-END execution path, not just each isolated component. Code-only review of gh#39 across multiple PRs verified watchdog scan + broadcast fan-out + DB INSERT + RLS scope (each isolated mechanism correct) but didn\'t trace the path through to SELF Monitor fire on the SELF target \u2014 which is where the gh#71 own-drone-filter gap silently blocked the wake. Apply when live-mechanism correctness is being claimed; trace the path the wake/value/state actually takes from origin to terminal observer.\n\n**Concrete verification surfaces by claim type:**\n- Version attribution \u2192 `git tag --contains <sha>` or `git log --oneline <tag>`\n- Code state \u2192 match the grep surface to the claim surface:\n - Local uncommitted claim \u2192 `grep -n "<symbol>" <file>` or direct file read in the working tree\n - `origin/main`, PR head, branch, merge-SHA, or tag claim \u2192 `git show <ref>:<path> | grep -n "<symbol>"` (examples: `git show origin/main:workers/heartbeat.ts | grep -n "last_log_post"`; `git show origin/feat/foo:client/src/log-stream.ts | grep -n "ownDrone"`; `git show abc1234:workers/cubes.ts | grep -n "visibility"`)\n- Prod state \u2192 `curl https://<endpoint>` or `wrangler tail --env production`\n- npm registry state \u2192 `npm view <package>@<version>` or `npm view <package>@latest`\n- DB state \u2192 query through the existing `db` interface; never trust a doc claim about row counts / column values\n- Cube log state \u2192 `borg_read-log unread_only=true` for wake triage, draining until `behind_by=0`; don\'t cite from memory or from another drone\'s summary\n\n**The discipline is universal to reviewer-class actions** (Code Reviewer formal gates + Security Auditor SR gates + PM-courtesy verifications + UX-courtesy reviews + any drone making a verification-worthy factual claim in their cube-log post). Refinement #13 lives in this playbook rather than in any one role\'s text because it applies to ALL reviewers.\n\n**Four-surface propagation (Refinement #13 sharpening \u2014 Sprint 8 PR-B + PR-D + Sprint 9 PR-A empirical evidence)**:\n\nThe discipline applies at FOUR surfaces. Catches at the surface closest to origin are cheapest; catches at later surfaces have already propagated through earlier consumers:\n\n- **Surface 1 (brainstorm-proposal time)**: when a brainstorm contribution names specific code identifiers / API field names / enum values / column names / function signatures, the PROPOSING drone source-grep\'s the referenced file BEFORE composing the proposal. If the proposal cites current `origin/main` or a branch/SHA, grep that ref via `git show <ref>:<path> | grep`; working-tree grep is only for explicitly local/uncommitted claims. Cheapest catch surface; one drone catches one error.\n- **Surface 2 (comment/JSDoc/docstring writing time)**: when an implementation comment cites cross-file invariants (other modules\' thresholds, schema columns, enum values, semantic contracts), the WRITING drone source-grep\'s the referenced file BEFORE writing the comment. If the comment describes a merged/base/PR-head state, grep the named ref via `git show <ref>:<path> | grep`; don\'t let a stale local checkout stand in for the ref being described. Mid-cost catch; one drone catches one error but downstream reviewers may inherit the wrong mental model from the comment.\n- **Surface 3 (review-time verification)**: the existing review-class discipline (Code Reviewer formal gates + Security Auditor SR gates + PM/UX/QA courtesy reviews). Late catch opportunity; if the error propagated through Surfaces 1 + 2, multiple reviewers may have already trusted the framing instead of source-grepping themselves.\n- **Surface 4 (durable-tracking-artifact-writing time)**: when filing a deferred-tracking gh issue from a cube event payload, the FILING drone fetches the originating entry\'s full body from the cube log BEFORE composing the issue body. For routine wake triage, use `borg_read-log unread_only=true` and drain until caught up; do not rely on a truncated event preview or a `since=<same timestamp>` read, which can skip the boundary entry. Cube event previews can truncate substantive content (mid-paragraph cuts on long entries); filing from the truncated preview trusts a derivative artifact instead of the source-of-truth full entry. Most expensive surface \u2014 the filed issue becomes the cube\'s durable cross-sprint memory; correcting it requires a follow-up issuecomment post-filing, and Sprint N+1 pickup drones inherit the incomplete framing if the correction is missed.\n\n**Empirical case studies (2026-05-17 Sprint 8 + Sprint 9)**: PR-B 5-drone cascade-failure on error-code casing \u2014 drone-8 proposed lowercase code names at brainstorm without grepping `workers/errors.ts:11 ErrorCode` enum (Surface 1 origin); drone-1 reproduced in dispatch verbatim; drone-6 implemented from dispatch; drone-2 CR + drone-3 QA initially approved without source-grepping (Surface 3 inherited the wrong framing); drone-8 caught their own origin gap at review-time via Surface 3 self-application. PR-D drone-2 CR-NIT #1 \u2014 drone-6 wrote JSDoc claim citing `gh#39 watchdog` semantics without grepping `workers/heartbeat.ts` (Surface 2 origin); drone-2 caught at Surface 3 review-time via direct file read. PR-#102 gh#103 filing \u2014 drone-1 filed gh#103 (PR #102 PM-NITs) composing the issue body from the TRUNCATED cube event preview of drone-7\'s 16:12:51Z entry (Surface 4 origin); NIT #2 substance dropped mid-paragraph; drone-7 closed the gap via issuecomment-4471465300 50 min post-filing. All three cases would have been cheapest to catch at the originating surface (1, 2, or 4 respectively).'}function x(e){const o=typeof e=="string"?new Date(e):e,r=Date.now()-o.getTime();if(!Number.isFinite(r)||r<0)return"just now";const i=Math.floor(r/1e3);if(i<60)return`${i}s ago`;const t=Math.floor(i/60);if(t<60)return`${t}m ago`;const n=Math.floor(t/60);return n<24?`${n}h ago`:`${Math.floor(n/24)}d ago`}function O(e){return e==null||Array.isArray(e)&&e.length===0?"Tip: no message taxonomy declared \u2014 set one to enable intent-based smart routing (#468). Use borg_update-cube with a taxonomy array, or add classes with borg_patch-taxonomy-class.":""}function M(e,o){return e.drone?.label??o??null}let h=!1,p=null,g=null;function U(){h=!1,p=null,g=null}function I(e){const o=e??"",r=y.filter(i=>o.includes(i));return[...b,...r]}function N(e,o){return`rationale \u2192 borg_role-rationale ${JSON.stringify(e)} ${JSON.stringify(o)}`}function q(e){const o=e.match(/borg_role-rationale\s+("(?:(?:\\.)|[^"\\])*")\s+("(?:(?:\\.)|[^"\\])*")/);if(!o)return null;try{return{role:JSON.parse(o[1]),section:JSON.parse(o[2])}}catch{return null}}const P=[...b,...y];function L(e,o){return T(o??"").map(t=>{if(t.kind!=="label"||t.heading==null||!t.heading.trim().toLowerCase().endsWith("rationale")||P.some(u=>t.body.includes(u)))return t.body;const s=t.body.indexOf(`
2
2
  `);return(s===-1?t.body+`
3
3
  `:t.body.slice(0,s+1))+N(e,t.heading)+`
4
- `}).join("")}function U(e,o={}){const i=o.mode??"full",n=e.roles.map(r=>`- **${r.name}**${r.is_default?" _(default)_":""} \u2014 ${r.short_description||"_(no short description)_"}`).join(`
5
- `),t=e.drones.map(r=>{const A=e.roles.find(D=>D.id===r.role_id),C=T(A?.name??"?",r.agent_kind);return`- **${r.label}** (${C}) \u2014 last seen ${I(new Date(r.last_seen))}`}).join(`
6
- `)||"_(no drones connected)_",a=new Map(e.drones.map(r=>[r.id,r])),s=new Map(e.roles.map(r=>[r.id,r])),g=e.recentLog.map(r=>F(r,a,s)).reverse().join(`
7
-
8
- `)||"_(no activity yet)_",_=e.recentLog.length===0&&e.drones.length<=1?["## Getting started","","Welcome to your first cube. Here's how to get going:","",'1. Post your first activity: `borg_log message="Starting work on <your task>"`',"2. Invite another agent session: open a new terminal and run `borg assimilate --worktree <name>`","3. Check who's here: `borg_roster`","","---",""].join(`
9
- `):"",f=O(e.cube.message_taxonomy),c=e.role.detailed_description_hash??null,l=e.cube.directive_hash??null,R=e.role.detailed_description?$(e.role.name,e.role.detailed_description):"_(no detailed description set)_",E=e.cube.cube_directive||"_(none)_",y=i==="full"||c==null||c!==h,b=i==="full"||l==null||l!==p,S=i==="full"||!u,d=[_+`# Cube: ${e.cube.name} \u2014 ${e.drone.label}`,"",`**Your role:** ${e.role.name}`,""];return i==="lite"&&d.push('_(lite regen \u2014 role playbook and cube directive may be omitted when unchanged. If they\'re NOT in your current context (e.g. after a context-compaction), call `borg_regen mode="full"` to re-orient.)_',""),d.push("## Cube directive",b?E:"_(unchanged since your last full/lite regen; omitted in lite mode)_","",...f?[f,""]:[],`## Your role: ${e.role.name}`,y?R:["_(role playbook unchanged since your last full/lite regen; omitted in lite mode)_","",...P(e.role.detailed_description)].join(`
10
- `),"","## Roles in this cube",n,"","## Connected drones",t,"","## Recent activity",g),S&&(d.push("",k()),u=!0),y&&c!=null&&(h=c),b&&l!=null&&(p=l),d.join(`
11
- `)}function F(e,o,i){const n=o.get(e.drone_id),t=n?i.get(n.role_id):null,a=new Date(e.created_at).toISOString(),s=typeof e.id=="string"&&e.id.length>0?` [entry_id: ${e.id}]`:"";return`**[${a}]**${s} ${n?.label??"?"} (${t?.name??"?"}): ${e.message}`}export{B as DRONE_PLAYBOOK,q as __resetRegenSessionState,$ as compressRoleText,F as formatLogEntryMarkdown,N as formatRationalePointer,U as formatRegenMarkdown,k as getDronePlaybook,I as humanAgo,O as nullTaxonomyTip,Q as parseRationalePointer,j as regenWakePathDroneLabel};
4
+ `}).join("")}function j(e,o={}){const r=o.mode??"full",i=e.roles.map(a=>`- **${a.name}**${a.is_default?" _(default)_":""} \u2014 ${a.short_description||"_(no short description)_"}`).join(`
5
+ `),t=e.drones.map(a=>{const S=e.roles.find(C=>C.id===a.role_id),A=D(S?.name??"?",a.agent_kind);return`- **${a.label}** (${A}) \u2014 last seen ${x(new Date(a.last_seen))}`}).join(`
6
+ `)||"_(no drones connected)_",n=typeof e.behind_by=="number"?e.behind_by:null,s=n===null?"Call `borg_read-log unread_only=true` to check for and drain any unread log entries (the log payload is not inlined in regen).":n>0?`You have **${n}** unread log ${n===1?"entry":"entries"}. Drain them with \`borg_read-log unread_only=true\` (oldest-unread first; repeat until \`behind_by=0\`). The log payload is not inlined here \u2014 fetch on demand.`:"You're caught up \u2014 **0** unread log entries. No need to read the log right now.",u=(n??0)===0&&e.drones.length<=1?["## Getting started","","Welcome to your first cube. Here's how to get going:","",'1. Post your first activity: `borg_log message="Starting work on <your task>"`',"2. Invite another agent session: open a new terminal and run `borg assimilate --worktree <name>`","3. Check who's here: `borg_roster`","","---",""].join(`
7
+ `):"",f=O(e.cube.message_taxonomy),l=e.role.detailed_description_hash??null,c=e.cube.directive_hash??null,k=e.role.detailed_description?L(e.role.name,e.role.detailed_description):"_(no detailed description set)_",_="Before you post or act, load your full operating context \u2014 once per session; static, do NOT re-fetch on every wake:\n- `borg_playbook` \u2014 your full operating disciplines (verification, four-surface propagation, ack / routing / idle detail).\n- `borg_cube` \u2014 the cube directive + conventions (log vocabulary, project / git / dispatch conventions).",m=r==="full"||l==null||l!==p,R=r==="full"||c==null||c!==g,E=r==="full"||!h,d=[u+`# Cube: ${e.cube.name} \u2014 ${e.drone.label}`,"",`**Your role:** ${e.role.name}`,""];return r==="lite"&&d.push('_(lite regen \u2014 the role playbook may be omitted when unchanged; your operating context (playbook + cube directive) loads via the Session-start block (borg_playbook + borg_cube). If the playbook is NOT in your current context (e.g. after a context-compaction), call `borg_regen mode="full"` to re-orient.)_',""),d.push("## Session start \u2014 required before acting",_,"",...f?[f,""]:[],`## Your role: ${e.role.name}`,m?k:["_(role playbook unchanged since your last full/lite regen; omitted in lite mode)_","",...I(e.role.detailed_description)].join(`
8
+ `),"","## Roles in this cube",i,"","## Connected drones",t,"","## Cube log",s),E&&(d.push("",v()),h=!0),m&&l!=null&&(p=l),R&&c!=null&&(g=c),d.join(`
9
+ `)}function Q(e,o,r){const i=o.get(e.drone_id),t=i?r.get(i.role_id):null,n=new Date(e.created_at).toISOString(),s=typeof e.id=="string"&&e.id.length>0?` [entry_id: ${e.id}]`:"";return`**[${n}]**${s} ${i?.label??"?"} (${t?.name??"?"}): ${e.message}`}export{B as DRONE_PLAYBOOK,U as __resetRegenSessionState,L as compressRoleText,Q as formatLogEntryMarkdown,N as formatRationalePointer,j as formatRegenMarkdown,v as getDronePlaybook,W as getDronePlaybookChapter,x as humanAgo,O as nullTaxonomyTip,q as parseRationalePointer,M as regenWakePathDroneLabel};
@@ -185,13 +185,16 @@ export declare function ackLogEntry(sessionToken: string, apiUrl: string, entryI
185
185
  *
186
186
  * Returns the active cube's directive, the drone's own role with full
187
187
  * detailed_description, the public role registry (no detailed_description
188
- * leakage for OTHER roles), the drone roster, and recent log entries.
189
- * Use on session start and before each new task to stay in sync.
188
+ * leakage for OTHER roles), the drone roster, and the caller's unread-log
189
+ * COUNT (behind_by). gh#886: the recent-log PAYLOAD is no longer rendered
190
+ * client-side — the drone gets the count and drains via borg_read-log. Use
191
+ * on session start and before each new task to stay in sync.
190
192
  *
191
193
  * gh#29 Sprint C / Q3a: optional `since` cursor (entry-id UUID or
192
- * ISO-8601 timestamp) trims the embedded recentLog to entries strictly
193
- * after the anchor closes the regen-overflow class when drones track
194
- * their last-seen entry across iterations.
194
+ * ISO-8601 timestamp). The worker still ships `recentLog` for rollout-compat
195
+ * (a pre-gh#886 client renders it; `since` trims it to entries strictly after
196
+ * the anchor) but the current client renders the unread COUNT, not the
197
+ * payload, so `since` no longer affects what this client shows.
195
198
  */
196
199
  export declare function regen(sessionToken: string, apiUrl: string, opts?: {
197
200
  since?: string;
@@ -201,7 +204,8 @@ export declare function regen(sessionToken: string, apiUrl: string, opts?: {
201
204
  drone: any;
202
205
  roles: any[];
203
206
  drones: any[];
204
- recentLog: any[];
207
+ recentLog?: any[];
208
+ behind_by?: number;
205
209
  }>;
206
210
  export declare function roleRationale(sessionToken: string, apiUrl: string, role: string, section: string): Promise<{
207
211
  role: string;
@@ -16,7 +16,7 @@
16
16
  /** Always-present escape hatch — reaches any borg tool regardless of scope. */
17
17
  export declare const DISPATCHER_TOOLS: readonly ["borg_tool", "borg_describe-tool"];
18
18
  /** Every role needs these; pre-loaded natively for all roles. */
19
- export declare const UNIVERSAL_TOOLS: readonly ["borg_regen", "borg_log", "borg_read-log", "borg_roster", "borg_stream-status", "borg_whoami", "borg_ack", "borg_version", "borg_cube", "borg_role", "borg_role-rationale", "borg_report-friction", "borg_assimilate", "borg_tool", "borg_describe-tool"];
19
+ export declare const UNIVERSAL_TOOLS: readonly ["borg_regen", "borg_log", "borg_read-log", "borg_roster", "borg_stream-status", "borg_whoami", "borg_ack", "borg_version", "borg_cube", "borg_role", "borg_role-rationale", "borg_report-friction", "borg_assimilate", "borg_playbook", "borg_tool", "borg_describe-tool"];
20
20
  /** Cube/role/drone management — native for management seats, deferred for workers. */
21
21
  export declare const MANAGEMENT_TOOLS: readonly ["borg_create-cube", "borg_update-cube", "borg_delete-cube", "borg_create-role", "borg_update-role", "borg_delete-role", "borg_patch-role-section", "borg_patch-taxonomy-class", "borg_reassign-drone", "borg_evict-drone", "borg_sync-roles", "borg_apply-template", "borg_list-cubes", "borg_list-drones", "borg_list-roles", "borg_list-templates"];
22
22
  /** Subscription/billing — native for management seats, deferred for workers. */
@@ -1 +1 @@
1
- const b=["borg_tool","borg_describe-tool"],a=["borg_regen","borg_log","borg_read-log","borg_roster","borg_stream-status","borg_whoami","borg_ack","borg_version","borg_cube","borg_role","borg_role-rationale","borg_report-friction","borg_assimilate",...b],_=["borg_create-cube","borg_update-cube","borg_delete-cube","borg_create-role","borg_update-role","borg_delete-role","borg_patch-role-section","borg_patch-taxonomy-class","borg_reassign-drone","borg_evict-drone","borg_sync-roles","borg_apply-template","borg_list-cubes","borg_list-drones","borg_list-roles","borg_list-templates"],g=["borg_subscribe","borg_upgrade-subscription","borg_subscription_status","borg_open_dashboard"],i=["borg_evict-drone","borg_delete-cube","borg_delete-role","borg_reassign-drone"];function n(r){return r.isHumanSeat===!0||r.roleClass==="queen"}function s(r){return!r||!r.roleName?new Set:n(r)?new Set:new Set([..._,...g])}function l(r,o){const e=s(o);return e.size===0?r:r.filter(t=>!e.has(t.name))}export{i as AUTH_SENSITIVE_TOOLS,g as BILLING_TOOLS,b as DISPATCHER_TOOLS,_ as MANAGEMENT_TOOLS,a as UNIVERSAL_TOOLS,s as deferredToolNames,l as filterToolsForRole,n as isManagementSeat};
1
+ const b=["borg_tool","borg_describe-tool"],a=["borg_regen","borg_log","borg_read-log","borg_roster","borg_stream-status","borg_whoami","borg_ack","borg_version","borg_cube","borg_role","borg_role-rationale","borg_report-friction","borg_assimilate","borg_playbook",...b],_=["borg_create-cube","borg_update-cube","borg_delete-cube","borg_create-role","borg_update-role","borg_delete-role","borg_patch-role-section","borg_patch-taxonomy-class","borg_reassign-drone","borg_evict-drone","borg_sync-roles","borg_apply-template","borg_list-cubes","borg_list-drones","borg_list-roles","borg_list-templates"],g=["borg_subscribe","borg_upgrade-subscription","borg_subscription_status","borg_open_dashboard"],l=["borg_evict-drone","borg_delete-cube","borg_delete-role","borg_reassign-drone"];function n(r){return r.isHumanSeat===!0||r.roleClass==="queen"}function s(r){return!r||!r.roleName?new Set:n(r)?new Set:new Set([..._,...g])}function i(r,o){const e=s(o);return e.size===0?r:r.filter(t=>!e.has(t.name))}export{l as AUTH_SENSITIVE_TOOLS,g as BILLING_TOOLS,b as DISPATCHER_TOOLS,_ as MANAGEMENT_TOOLS,a as UNIVERSAL_TOOLS,s as deferredToolNames,i as filterToolsForRole,n as isManagementSeat};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "borgmcp",
3
- "version": "1.0.36",
3
+ "version": "1.0.38",
4
4
  "description": "Coordinate AI coding agents in shared cubes. Works with Claude Code and Codex. Create projects, assign roles, and share a live activity log.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",