@productbrain/mcp 0.0.1-beta.14234 → 0.0.1-beta.14267

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.
@@ -6927,9 +6927,10 @@ async function fetchAndRenderOpenerDirection(kernelQuery2, errors, session) {
6927
6927
  }
6928
6928
  return { lines: [...buildOrientBriefingLines(view), ...buildRitualsSurfaceLines(view, { fetchFailed: fetchFailed || view?.fetchFailed === true })], view };
6929
6929
  }
6930
- async function buildAlreadyOrientedResult(kernelQuery2, agentSessionId, taskGroundingWarningLines2) {
6930
+ async function buildAlreadyOrientedResult(kernelQuery2, agentSessionId, taskGroundingWarningLines2, boundScopeLines2 = Promise.resolve([])) {
6931
6931
  const errors = [];
6932
6932
  const { lines, view } = await fetchAndRenderOpenerDirection(kernelQuery2, errors, { agentSessionId, invocationPath: "manual-orient" });
6933
+ for (const line of await boundScopeLines2) lines.push(line);
6933
6934
  return {
6934
6935
  content: [{
6935
6936
  type: "text",
@@ -6975,6 +6976,178 @@ function reportOrientWrapperBytes(toolResult, truncated, tier, taskProvided) {
6975
6976
  }
6976
6977
  }
6977
6978
 
6979
+ // src/lib/boundScope.ts
6980
+ import { execFile } from "child_process";
6981
+ import { readFileSync as readFileSync3 } from "fs";
6982
+ var WORKSPACE_SCOPE_BINDING_VERSION = 1;
6983
+ var WORKSPACE_SCOPE_RELATIVE_PATH = ".productbrain/.local/workspace-scope.json";
6984
+ var BOUND_PACKAGE_ID = /^(?:WP|BET)-\d+$/;
6985
+ var WorkspaceCompletionError = class extends Error {
6986
+ name = "WorkspaceCompletionError";
6987
+ };
6988
+ function isRecord(value) {
6989
+ return value !== null && typeof value === "object" && !Array.isArray(value);
6990
+ }
6991
+ function requiredString(value, label) {
6992
+ if (typeof value !== "string" || value.trim().length === 0) throw new WorkspaceCompletionError(`Workspace scope binding has no valid ${label}.`);
6993
+ return value;
6994
+ }
6995
+ function normalizeOwnedSliceIds(value) {
6996
+ if (!Array.isArray(value) || value.length === 0) throw new WorkspaceCompletionError("Workspace scope binding ownedSliceIds must be a non-empty list of TASK-NNN ids.");
6997
+ const bad = value.findIndex((id) => typeof id !== "string" || !/^TASK-\d+$/.test(id));
6998
+ if (bad >= 0) throw new WorkspaceCompletionError(`${String(value[bad])} is not a TASK-NNN id; a workspace owns tasks only (ownedSliceIds).`);
6999
+ return [...new Set(value)];
7000
+ }
7001
+ function parseWorkspaceScopeBinding(raw) {
7002
+ let parsed;
7003
+ try {
7004
+ parsed = JSON.parse(raw);
7005
+ } catch {
7006
+ throw new WorkspaceCompletionError("Workspace scope binding is malformed JSON.");
7007
+ }
7008
+ if (!isRecord(parsed)) throw new WorkspaceCompletionError("Workspace scope binding must be a JSON object.");
7009
+ if (parsed["version"] !== WORKSPACE_SCOPE_BINDING_VERSION) throw new WorkspaceCompletionError(`Unsupported workspace scope binding version: ${String(parsed["version"])}.`);
7010
+ const scopeEntryId = requiredString(parsed["scopeEntryId"], "scopeEntryId");
7011
+ if (!BOUND_PACKAGE_ID.test(scopeEntryId)) throw new WorkspaceCompletionError(`Workspace scope binding entry must be a WP-NNN or legacy BET-NNN ID; got ${scopeEntryId}.`);
7012
+ const boundAt = requiredString(parsed["boundAt"], "boundAt");
7013
+ if (Number.isNaN(Date.parse(boundAt))) throw new WorkspaceCompletionError("Workspace scope binding has an invalid boundAt timestamp.");
7014
+ return {
7015
+ version: WORKSPACE_SCOPE_BINDING_VERSION,
7016
+ scopeEntryId,
7017
+ scopeName: requiredString(parsed["scopeName"], "scopeName"),
7018
+ chainWorkspaceId: requiredString(parsed["chainWorkspaceId"], "chainWorkspaceId"),
7019
+ boundAt,
7020
+ ..."ownedSliceIds" in parsed ? { ownedSliceIds: normalizeOwnedSliceIds(parsed["ownedSliceIds"]) } : {}
7021
+ };
7022
+ }
7023
+ var BIND_AGAIN = "npm run workspace:bind -- <WP-ID> [TASK-ID ...]";
7024
+ var BOUND_SCOPE_WORDS = {
7025
+ heading: "## Bound scope",
7026
+ /** RULE-17: ticks are counted against the task's whole done-when list. */
7027
+ ticks: (ticked, total) => total === 0 ? "no done-when" : `${ticked} of ${total} done-when ticked`,
7028
+ noStage: "no stage",
7029
+ notFound: "not found in this workspace; check the id in the bind file, or bind again",
7030
+ /** The credential reads another workspace than the lane was bound in (as assertParentIdentity refuses in the lane scripts). */
7031
+ otherWorkspace: (ids) => `Read from another workspace than this lane's bind: ${ids.join(", ")}. Run \`pb profile use <name>\` for the lane's workspace, or bind again: ${BIND_AGAIN}`,
7032
+ notRead: (entryId, reason2) => `${entryId} not read: ${reason2}`,
7033
+ wholePackage: "No tasks named at bind: the lane owns the whole package.",
7034
+ pr: (branch, pr) => `Open PR on ${branch}: #${pr.number} at ${pr.headSha.slice(0, 9)} \xB7 ${pr.labels.join(", ") || "no labels"}`,
7035
+ noPr: (branch) => `No open PR on ${branch}.`,
7036
+ prsNotRead: (reason2) => `PRs not read: ${reason2}.`,
7037
+ ghMissing: "gh is not installed; install gh, or read the PRs on GitHub",
7038
+ /** gh's own first line; the auth step only when that line is about signing in. */
7039
+ ghFailed: (detail) => `gh failed (${detail})${/auth|log ?in|token|credential/i.test(detail) ? "; gh auth status says whether it is signed in" : ""}`,
7040
+ noBranch: "this worktree is on no branch; check out the lane branch",
7041
+ fileError: (message) => `The bind file could not be read. ${WORKSPACE_SCOPE_RELATIVE_PATH}: ${message} Fix it, or remove it and bind again: ${BIND_AGAIN}`
7042
+ };
7043
+ var TIMEOUT_MS = { git: 3e3, gh: 8e3 };
7044
+ function nodeBoundScopeIo(cwd, readEntries) {
7045
+ const run = (command, args, dir) => new Promise((resolve5) => {
7046
+ execFile(command, args, { cwd: dir, timeout: TIMEOUT_MS[command], encoding: "utf8", windowsHide: true }, (error, stdout, stderr) => {
7047
+ if (!error) return resolve5({ ok: true, stdout });
7048
+ const detail = (stderr.trim().split("\n")[0] || (error.killed ? "no answer in time" : error.message)).trim();
7049
+ resolve5({ ok: false, detail, ...error.code === "ENOENT" ? { missing: true } : {} });
7050
+ });
7051
+ });
7052
+ const readText = (path) => {
7053
+ try {
7054
+ return readFileSync3(path, "utf8");
7055
+ } catch (error) {
7056
+ if (error.code === "ENOENT") return null;
7057
+ throw error;
7058
+ }
7059
+ };
7060
+ return { cwd, readText, run, readEntries };
7061
+ }
7062
+ var messageOf = (error) => error instanceof Error ? error.message : String(error);
7063
+ function rowOf(entryId, answer2, isTask, workspaceId) {
7064
+ const entry = answer2?.entry;
7065
+ if (!isRecord(entry)) return { entryId, notRead: BOUND_SCOPE_WORDS.notFound };
7066
+ if (entry["workspaceId"] !== workspaceId) return { entryId, otherWorkspace: true };
7067
+ const data = isRecord(entry["data"]) ? entry["data"] : {};
7068
+ const items = Array.isArray(data["doneWhen"]) ? data["doneWhen"] : [];
7069
+ return {
7070
+ entryId,
7071
+ ...typeof entry["name"] === "string" ? { name: entry["name"] } : {},
7072
+ ...typeof entry["workflowStatus"] === "string" ? { workflowStatus: entry["workflowStatus"] } : {},
7073
+ ...isTask ? { doneWhen: { ticked: items.filter((item) => isRecord(item) && item["done"] === true).length, total: items.length } } : { priority: data["priority"] }
7074
+ };
7075
+ }
7076
+ async function readRows(io, ids, workspaceId) {
7077
+ try {
7078
+ const chunks = Array.from({ length: Math.ceil(ids.length / 20) }, (_, i) => ids.slice(i * 20, (i + 1) * 20));
7079
+ const answers = (await Promise.all(chunks.map((chunk) => io.readEntries(chunk)))).flat();
7080
+ return ids.map((id, i) => rowOf(id, answers[i], i > 0, workspaceId));
7081
+ } catch (error) {
7082
+ return ids.map((entryId) => ({ entryId, notRead: messageOf(error) }));
7083
+ }
7084
+ }
7085
+ async function readPrs(io, root, branch) {
7086
+ if (!branch) return { prsNotRead: BOUND_SCOPE_WORDS.noBranch };
7087
+ const result2 = await io.run("gh", ["pr", "list", "--head", branch, "--state", "open", "--json", "number,headRefOid,labels"], root);
7088
+ if (!result2.ok) return { prsNotRead: result2.missing ? BOUND_SCOPE_WORDS.ghMissing : BOUND_SCOPE_WORDS.ghFailed(result2.detail) };
7089
+ try {
7090
+ const parsed = JSON.parse(result2.stdout);
7091
+ if (!Array.isArray(parsed)) throw new Error("not a list");
7092
+ return {
7093
+ prs: parsed.filter(isRecord).map((pr) => ({
7094
+ number: Number(pr["number"]),
7095
+ headSha: typeof pr["headRefOid"] === "string" ? pr["headRefOid"] : "",
7096
+ labels: (Array.isArray(pr["labels"]) ? pr["labels"] : []).flatMap((label) => isRecord(label) && typeof label["name"] === "string" ? [label["name"]] : [])
7097
+ }))
7098
+ };
7099
+ } catch (error) {
7100
+ return { prsNotRead: BOUND_SCOPE_WORDS.ghFailed(`its answer was not a PR list: ${messageOf(error)}`) };
7101
+ }
7102
+ }
7103
+ async function readBoundScope(io) {
7104
+ const top = await io.run("git", ["rev-parse", "--show-toplevel", "--abbrev-ref", "HEAD"], io.cwd);
7105
+ if (!top.ok) return null;
7106
+ const [root = "", head = ""] = top.stdout.trim().split("\n").map((line) => line.trim());
7107
+ let binding;
7108
+ try {
7109
+ const raw = root ? io.readText(`${root}/${WORKSPACE_SCOPE_RELATIVE_PATH}`) : null;
7110
+ if (raw === null) return null;
7111
+ binding = parseWorkspaceScopeBinding(raw);
7112
+ } catch (error) {
7113
+ return { fileError: messageOf(error) };
7114
+ }
7115
+ const branch = head && head !== "HEAD" ? head : null;
7116
+ const [rows, prs] = await Promise.all([readRows(io, [binding.scopeEntryId, ...binding.ownedSliceIds ?? []], binding.chainWorkspaceId), readPrs(io, root, branch)]);
7117
+ return { scopeEntryId: binding.scopeEntryId, rows, ownsWholePackage: !binding.ownedSliceIds, branch, ...prs };
7118
+ }
7119
+ function rowLine(row, isTask) {
7120
+ if (row.notRead) return BOUND_SCOPE_WORDS.notRead(row.entryId, row.notRead);
7121
+ const token = priorityOf(row.priority);
7122
+ const tail = isTask ? BOUND_SCOPE_WORDS.ticks(row.doneWhen?.ticked ?? 0, row.doneWhen?.total ?? 0) : token ? PRIORITY_LEVELS[token].word : NO_PRIORITY.word;
7123
+ return `${row.entryId}${row.name ? ` \u2014 ${row.name}` : ""} \xB7 ${row.workflowStatus ?? BOUND_SCOPE_WORDS.noStage} \xB7 ${tail}`;
7124
+ }
7125
+ function boundScopeLines(view) {
7126
+ const lines = [BOUND_SCOPE_WORDS.heading, ""];
7127
+ const item = (line) => lines.push(` \u2022 ${line}`);
7128
+ if ("fileError" in view) item(BOUND_SCOPE_WORDS.fileError(view.fileError));
7129
+ else {
7130
+ view.rows.forEach((row, i) => {
7131
+ if (!row.otherWorkspace) item(rowLine(row, i > 0));
7132
+ });
7133
+ const elsewhere = view.rows.filter((row) => row.otherWorkspace).map((row) => row.entryId);
7134
+ if (elsewhere.length > 0) item(BOUND_SCOPE_WORDS.otherWorkspace(elsewhere));
7135
+ if (view.ownsWholePackage) item(BOUND_SCOPE_WORDS.wholePackage);
7136
+ if (view.prsNotRead !== void 0) item(BOUND_SCOPE_WORDS.prsNotRead(view.prsNotRead));
7137
+ else if (view.branch && view.prs?.length) for (const pr of view.prs) item(BOUND_SCOPE_WORDS.pr(view.branch, pr));
7138
+ else if (view.branch) item(BOUND_SCOPE_WORDS.noPr(view.branch));
7139
+ }
7140
+ return lines;
7141
+ }
7142
+
7143
+ // src/tools/orient-bound-scope.ts
7144
+ function readMcpBoundScope() {
7145
+ return readBoundScope(nodeBoundScopeIo(process.cwd(), (entryIds) => kernelQuery("chain.batchGetEntries", { entryIds })));
7146
+ }
7147
+ function boundScopeBlock(view) {
7148
+ return view ? ["", ...boundScopeLines(view)] : [];
7149
+ }
7150
+
6978
7151
  // src/tools/orientDegradation.ts
6979
7152
  function buildDegradedPreloadsLine(degraded) {
6980
7153
  if (!degraded || degraded.length === 0) return null;
@@ -7118,8 +7291,9 @@ async function _handleOrient({ mode: mode2 = "full", tier, task, startupSignals,
7118
7291
  const errors = [];
7119
7292
  const callTier = tier ?? (mode2 === "brief" ? "summary" : void 0);
7120
7293
  const agentSessionId = getAgentSessionId();
7294
+ const boundScopeRead = readMcpBoundScope();
7121
7295
  if (isSessionOriented() && mode2 === "brief" && !task && !rules) {
7122
- return buildAlreadyOrientedResult(kernelQuery, agentSessionId, taskGroundingWarningLines());
7296
+ return buildAlreadyOrientedResult(kernelQuery, agentSessionId, taskGroundingWarningLines(), boundScopeRead.then(boundScopeBlock));
7123
7297
  }
7124
7298
  let wsCtx = null;
7125
7299
  try {
@@ -7205,11 +7379,9 @@ async function _handleOrient({ mode: mode2 = "full", tier, task, startupSignals,
7205
7379
  }
7206
7380
  const lines = sampleTruncated ? [READINESS_PROVISIONAL_LINE, ""] : [];
7207
7381
  if (wsCtx) {
7208
- lines.push(`# ${wsCtx.workspaceName}`);
7209
- lines.push(`_Workspace \`${wsCtx.workspaceSlug}\` \u2014 Product Brain is healthy._`);
7382
+ lines.push(`# ${wsCtx.workspaceName}`, `_Workspace \`${wsCtx.workspaceSlug}\` \u2014 Product Brain is healthy._`);
7210
7383
  } else {
7211
- lines.push("# Workspace");
7212
- lines.push("_Could not resolve workspace._");
7384
+ lines.push("# Workspace", "_Could not resolve workspace._");
7213
7385
  }
7214
7386
  lines.push("");
7215
7387
  lines.push(...taskGroundingWarningLines(task, hasTaskGrounding));
@@ -7220,6 +7392,7 @@ async function _handleOrient({ mode: mode2 = "full", tier, task, startupSignals,
7220
7392
  }
7221
7393
  if (mode2 === "brief") {
7222
7394
  for (const line of buildOrientBriefingLines(orientView)) lines.push(line);
7395
+ for (const line of boundScopeBlock(await boundScopeRead)) lines.push(line);
7223
7396
  if (orientView?.strategicContext) {
7224
7397
  const sc = orientView.strategicContext;
7225
7398
  if (sc.playingFieldCount != null && sc.playingFieldCount > 0) {
@@ -7371,6 +7544,7 @@ async function _handleOrient({ mode: mode2 = "full", tier, task, startupSignals,
7371
7544
  lines.push("_Need a collection that doesn't exist yet? Creating one is not available through this tool. Ask a platform admin to provision it, or enable the module ontology pack that owns it._");
7372
7545
  lines.push("");
7373
7546
  for (const line of buildOrientBriefingLines(orientView)) lines.push(line);
7547
+ for (const line of boundScopeBlock(await boundScopeRead)) lines.push(line);
7374
7548
  lines.push("");
7375
7549
  let fullCoherenceSnapshot;
7376
7550
  if (readiness) {
@@ -9374,14 +9548,14 @@ function parseListOutput(output) {
9374
9548
  import { z as z25 } from "zod/v3";
9375
9549
 
9376
9550
  // src/lib/spineVerdictRead.ts
9377
- function isRecord(value) {
9551
+ function isRecord2(value) {
9378
9552
  return typeof value === "object" && value !== null && !Array.isArray(value);
9379
9553
  }
9380
9554
  function isStringArray(value) {
9381
9555
  return Array.isArray(value) && value.every((item) => typeof item === "string");
9382
9556
  }
9383
9557
  function isStructural(value) {
9384
- if (!isRecord(value) || typeof value.passed !== "boolean" || !isStringArray(value.missing) || !isRecord(value.duplicateSingletons) || !isStringArray(value.unconnectedStrategyIds) || value.visionConnectedToPurpose !== null && typeof value.visionConnectedToPurpose !== "boolean") return false;
9558
+ if (!isRecord2(value) || typeof value.passed !== "boolean" || !isStringArray(value.missing) || !isRecord2(value.duplicateSingletons) || !isStringArray(value.unconnectedStrategyIds) || value.visionConnectedToPurpose !== null && typeof value.visionConnectedToPurpose !== "boolean") return false;
9385
9559
  for (const key of ["purpose", "vision"]) {
9386
9560
  const ids = value.duplicateSingletons[key];
9387
9561
  if (ids !== null && !isStringArray(ids)) return false;
@@ -9396,18 +9570,18 @@ function isStructural(value) {
9396
9570
  if (value[key] != null && !isStringArray(value[key])) return false;
9397
9571
  }
9398
9572
  const stranded = value.strandedWorkPackages;
9399
- if (stranded != null && !(Array.isArray(stranded) && stranded.every((w) => isRecord(w) && typeof w.id === "string" && isStringArray(w.pastTargetIds)))) return false;
9573
+ if (stranded != null && !(Array.isArray(stranded) && stranded.every((w) => isRecord2(w) && typeof w.id === "string" && isStringArray(w.pastTargetIds)))) return false;
9400
9574
  return value.visionPurposeConnectivityTruncated === void 0 || typeof value.visionPurposeConnectivityTruncated === "boolean";
9401
9575
  }
9402
9576
  function isStrategy(value) {
9403
- if (!isRecord(value) || typeof value.entryId !== "string" || !isRecord(value.refusal) || typeof value.refusal.hasRefusalSignal !== "boolean") return false;
9404
- return value.rogerMartin === null || isRecord(value.rogerMartin) && typeof value.rogerMartin.isStrategicChoice === "boolean" && typeof value.rogerMartin.reasoning === "string";
9577
+ if (!isRecord2(value) || typeof value.entryId !== "string" || !isRecord2(value.refusal) || typeof value.refusal.hasRefusalSignal !== "boolean") return false;
9578
+ return value.rogerMartin === null || isRecord2(value.rogerMartin) && typeof value.rogerMartin.isStrategicChoice === "boolean" && typeof value.rogerMartin.reasoning === "string";
9405
9579
  }
9406
9580
  function isStory(value) {
9407
- return value === null || isRecord(value) && typeof value.passed === "boolean" && (value.failedCriterion === null || typeof value.failedCriterion === "string") && Array.isArray(value.criteria) && value.criteria.every((item) => isRecord(item) && typeof item.id === "string" && typeof item.passed === "boolean" && typeof item.reasoning === "string");
9581
+ return value === null || isRecord2(value) && typeof value.passed === "boolean" && (value.failedCriterion === null || typeof value.failedCriterion === "string") && Array.isArray(value.criteria) && value.criteria.every((item) => isRecord2(item) && typeof item.id === "string" && typeof item.passed === "boolean" && typeof item.reasoning === "string");
9408
9582
  }
9409
9583
  function readSpineVerdict(value) {
9410
- if (!isRecord(value) || typeof value.noSpineEntries !== "boolean") return { kind: "malformed" };
9584
+ if (!isRecord2(value) || typeof value.noSpineEntries !== "boolean") return { kind: "malformed" };
9411
9585
  if (value.noSpineEntries) return { kind: "empty" };
9412
9586
  if (!isStructural(value.structural) || !Array.isArray(value.perStrategy) || !value.perStrategy.every(isStrategy) || !isStory(value.story)) return { kind: "malformed" };
9413
9587
  for (const key of ["strategiesTruncated", "perStrategyEvaluationTruncated", "objectivesTruncated", "keyResultsTruncated", "workPackagesTruncated"]) {
@@ -12114,4 +12288,4 @@ export {
12114
12288
  SERVER_VERSION,
12115
12289
  createProductBrainServer
12116
12290
  };
12117
- //# sourceMappingURL=chunk-CSF3YZ2Q.js.map
12291
+ //# sourceMappingURL=chunk-AY65CB45.js.map