psyclaw 0.31.5 → 0.34.0-preview.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/dist/apps/panel/index.html +16 -16
  2. package/dist/src/adapters/pi/arg-repair.d.ts +27 -0
  3. package/dist/src/adapters/pi/arg-repair.js +177 -0
  4. package/dist/src/adapters/pi/arg-repair.js.map +1 -0
  5. package/dist/src/adapters/pi/extension.js +1499 -493
  6. package/dist/src/adapters/pi/extension.js.map +1 -1
  7. package/dist/src/adapters/pi/observation-mask.d.ts +19 -0
  8. package/dist/src/adapters/pi/observation-mask.js +105 -2
  9. package/dist/src/adapters/pi/observation-mask.js.map +1 -1
  10. package/dist/src/adapters/pi/session.js +1 -1
  11. package/dist/src/adapters/pi/session.js.map +1 -1
  12. package/dist/src/analysis/decision-points.d.ts +4 -9
  13. package/dist/src/analysis/decision-points.js +20 -67
  14. package/dist/src/analysis/decision-points.js.map +1 -1
  15. package/dist/src/analysis/estimand.d.ts +127 -0
  16. package/dist/src/analysis/estimand.js +526 -0
  17. package/dist/src/analysis/estimand.js.map +1 -0
  18. package/dist/src/analysis/method-rules.d.ts +6 -0
  19. package/dist/src/analysis/method-rules.js +20 -3
  20. package/dist/src/analysis/method-rules.js.map +1 -1
  21. package/dist/src/analysis/package-net.d.ts +106 -0
  22. package/dist/src/analysis/package-net.js +277 -0
  23. package/dist/src/analysis/package-net.js.map +1 -0
  24. package/dist/src/analysis/plan.d.ts +6 -2
  25. package/dist/src/analysis/plan.js +34 -17
  26. package/dist/src/analysis/plan.js.map +1 -1
  27. package/dist/src/analysis/runtime-tools.d.ts +0 -6
  28. package/dist/src/analysis/runtime-tools.js +0 -156
  29. package/dist/src/analysis/runtime-tools.js.map +1 -1
  30. package/dist/src/analysis/shell-timeout.d.ts +21 -0
  31. package/dist/src/analysis/shell-timeout.js +87 -1
  32. package/dist/src/analysis/shell-timeout.js.map +1 -1
  33. package/dist/src/analysis/stats-router.d.ts +4 -8
  34. package/dist/src/analysis/stats-router.js +21 -23
  35. package/dist/src/analysis/stats-router.js.map +1 -1
  36. package/dist/src/ars/academic-router.d.ts +8 -8
  37. package/dist/src/ars/academic-router.js +22 -35
  38. package/dist/src/ars/academic-router.js.map +1 -1
  39. package/dist/src/ars/doctor.js +1 -2
  40. package/dist/src/ars/doctor.js.map +1 -1
  41. package/dist/src/ars/mode-editor.d.ts +7 -2
  42. package/dist/src/ars/mode-editor.js +15 -16
  43. package/dist/src/ars/mode-editor.js.map +1 -1
  44. package/dist/src/branding.d.ts +10 -0
  45. package/dist/src/branding.js +40 -32
  46. package/dist/src/branding.js.map +1 -1
  47. package/dist/src/chat.d.ts +1 -1
  48. package/dist/src/chat.js +12 -2
  49. package/dist/src/chat.js.map +1 -1
  50. package/dist/src/index.d.ts +1 -2
  51. package/dist/src/index.js +1 -2
  52. package/dist/src/index.js.map +1 -1
  53. package/dist/src/install/installer.js +0 -5
  54. package/dist/src/install/installer.js.map +1 -1
  55. package/dist/src/integrations/mcp-format.d.ts +6 -0
  56. package/dist/src/integrations/mcp-format.js +52 -0
  57. package/dist/src/integrations/mcp-format.js.map +1 -0
  58. package/dist/src/observability/langfuse.js +201 -5
  59. package/dist/src/observability/langfuse.js.map +1 -1
  60. package/dist/src/orchestration/research-agents.js +1 -1
  61. package/dist/src/orchestration/research-agents.js.map +1 -1
  62. package/dist/src/orchestration/runner.d.ts +0 -1
  63. package/dist/src/orchestration/runner.js +0 -3
  64. package/dist/src/orchestration/runner.js.map +1 -1
  65. package/dist/src/orchestration/scheduler.js +0 -31
  66. package/dist/src/orchestration/scheduler.js.map +1 -1
  67. package/dist/src/panel/server.js +3 -3
  68. package/dist/src/panel/server.js.map +1 -1
  69. package/dist/src/project/hitl.js +3 -3
  70. package/dist/src/project/hitl.js.map +1 -1
  71. package/dist/src/project/workspace.js +8 -20
  72. package/dist/src/project/workspace.js.map +1 -1
  73. package/dist/src/research/decisions.d.ts +115 -0
  74. package/dist/src/research/decisions.js +284 -0
  75. package/dist/src/research/decisions.js.map +1 -0
  76. package/dist/src/research/intent.d.ts +90 -0
  77. package/dist/src/research/intent.js +175 -0
  78. package/dist/src/research/intent.js.map +1 -0
  79. package/dist/src/research/plan-message.d.ts +117 -0
  80. package/dist/src/research/plan-message.js +187 -0
  81. package/dist/src/research/plan-message.js.map +1 -0
  82. package/dist/src/research/practice.d.ts +33 -0
  83. package/dist/src/research/practice.js +160 -0
  84. package/dist/src/research/practice.js.map +1 -0
  85. package/dist/src/router/decision-model.d.ts +54 -0
  86. package/dist/src/router/decision-model.js +129 -0
  87. package/dist/src/router/decision-model.js.map +1 -0
  88. package/dist/src/rules/user-rules.js.map +1 -1
  89. package/dist/src/safety/data-access.js +4 -4
  90. package/dist/src/safety/data-access.js.map +1 -1
  91. package/dist/src/safety/secret-marks.d.ts +44 -0
  92. package/dist/src/safety/secret-marks.js +88 -0
  93. package/dist/src/safety/secret-marks.js.map +1 -0
  94. package/dist/src/session/continuously-work.js +1 -1
  95. package/dist/src/session/continuously-work.js.map +1 -1
  96. package/dist/src/session/help.js +29 -32
  97. package/dist/src/session/help.js.map +1 -1
  98. package/dist/src/session/modes.d.ts +24 -17
  99. package/dist/src/session/modes.js +81 -94
  100. package/dist/src/session/modes.js.map +1 -1
  101. package/dist/src/session/skill-invoke.d.ts +54 -0
  102. package/dist/src/session/skill-invoke.js +177 -0
  103. package/dist/src/session/skill-invoke.js.map +1 -0
  104. package/dist/src/session/skill-reference.d.ts +15 -0
  105. package/dist/src/session/skill-reference.js +35 -0
  106. package/dist/src/session/skill-reference.js.map +1 -0
  107. package/dist/src/skills/recommended.js +0 -1
  108. package/dist/src/skills/recommended.js.map +1 -1
  109. package/dist/src/skills/user-skills.js +11 -0
  110. package/dist/src/skills/user-skills.js.map +1 -1
  111. package/dist/src/style/cli-ui.js +15 -12
  112. package/dist/src/style/cli-ui.js.map +1 -1
  113. package/dist/src/tui/biosignal-wizard.js +1 -1
  114. package/dist/src/tui/biosignal-wizard.js.map +1 -1
  115. package/dist/src/tui/wake-options.d.ts +2 -2
  116. package/dist/src/tui/wake-options.js +8 -5
  117. package/dist/src/tui/wake-options.js.map +1 -1
  118. package/dist/src/updates/check.js +4 -2
  119. package/dist/src/updates/check.js.map +1 -1
  120. package/dist/src/updates/registry.d.ts +2 -1
  121. package/dist/src/updates/registry.js +2 -2
  122. package/dist/src/updates/registry.js.map +1 -1
  123. package/dist/src/updates/status.d.ts +9 -2
  124. package/dist/src/updates/status.js +43 -6
  125. package/dist/src/updates/status.js.map +1 -1
  126. package/dist/src/updates/update.js +7 -3
  127. package/dist/src/updates/update.js.map +1 -1
  128. package/dist/src/updates/whats-new.js +12 -0
  129. package/dist/src/updates/whats-new.js.map +1 -1
  130. package/dist/src/verify/checklist.d.ts +1 -1
  131. package/dist/src/verify/checklist.js +5 -5
  132. package/dist/src/verify/checklist.js.map +1 -1
  133. package/dist/src/wake-options/runtime.d.ts +9 -0
  134. package/dist/src/wake-options/runtime.js +39 -1
  135. package/dist/src/wake-options/runtime.js.map +1 -1
  136. package/dist/src/workflows/academic-export.js.map +1 -1
  137. package/dist/src/workflows/meta-analysis.js +1 -1
  138. package/dist/src/workflows/meta-analysis.js.map +1 -1
  139. package/package.json +2 -1
  140. package/skills/core/academic-grill/SKILL.md +3 -3
  141. package/skills/core/analysis-plan/SKILL.md +35 -32
  142. package/skills/core/manifest.json +12 -4
  143. package/skills/core/package-install/SKILL.md +35 -0
  144. package/skills/core/package-install/pkgnet.py +178 -0
  145. package/skills/recommended/mcp-catalog.json +1 -1
  146. package/dist/src/research/choice.d.ts +0 -16
  147. package/dist/src/research/choice.js +0 -25
  148. package/dist/src/research/choice.js.map +0 -1
  149. package/dist/src/skills/registry.d.ts +0 -28
  150. package/dist/src/skills/registry.js +0 -550
  151. package/dist/src/skills/registry.js.map +0 -1
@@ -1,13 +1,21 @@
1
- import { DefaultPackageManager, getAgentDir, SettingsManager } from "@earendil-works/pi-coding-agent";
2
- import { isInstructionResult, isObservationEvidence, maskToolObservationsStable, observationSettledLimit } from "./observation-mask.js";
1
+ import { createEditToolDefinition, DefaultPackageManager, getAgentDir, SettingsManager } from "@earendil-works/pi-coding-agent";
2
+ import { withArgRepair } from "./arg-repair.js";
3
+ import { applyAnswers, applyReply, ATTR_ZH, cardItems, cardText, planMessage as estimandPlanMessage, toConfirm as estimandsToConfirm, gaps as estimandGaps, loadSpec, MAX_CONFIRMS, materialsText, recordResult, researchQuestionLabels, saveSpec, settleByRecommendation, SPEC_JSON, SPEC_MD, stale as estimandStale, writeSpec } from "../../analysis/estimand.js";
4
+ import { APPROVAL_QUESTION, ASK_RESEARCHER_QUESTION, DecisionModel, HAS_QUESTION_QUESTION, ROUTE_QUESTION, WRITING_SKILL_QUESTION } from "../../router/decision-model.js";
5
+ import { lacksResearchQuestion } from "../../analysis/stats-router.js";
6
+ import { isInstructionResult, isObservationEvidence, maskedPlaceholderReason, maskHeavyParts, maskToolObservationsStable, observationSettledLimit } from "./observation-mask.js";
3
7
  import { outputLogFooter, persistToolOutput } from "../../analysis/output-log.js";
4
- import { applyShellTimeout, isShellTimeout, SHELL_TIMEOUT_HINT, ShellClock } from "../../analysis/shell-timeout.js";
8
+ import { applyShellTimeout, isShellTimeout, moveTimeoutPrefix, scriptInCommand, ShellClock } from "../../analysis/shell-timeout.js";
9
+ import { decisionPointsNotice } from "../../analysis/decision-points.js";
10
+ import { backgroundInstallMinutes, condaChannels, condaTargets, cranProfile, cranTargets, describeRoute, fastest, installTimeoutSeconds, isRInstall, PackageNet, parsePipInstall, probeSpeeds, routeCommand, routeCondaCommand, routeRCommand, shellQuote, startBackgroundInstall } from "../../analysis/package-net.js";
5
11
  import { registerAnalysisRuntimeTools } from "../../analysis/runtime-tools.js";
6
- import { PSYCLAW_VERSION } from "../../branding.js";
12
+ import { PSYCLAW_BASIC_PROMPT, PSYCLAW_IDENTITY_PROMPT, PSYCLAW_VERSION, PSYCLAW_WRITING_RULES } from "../../branding.js";
7
13
  import { takeWhatsNew } from "../../updates/whats-new.js";
8
14
  import { formatDataAccess, loadDataAccess, redactScriptOnlyOutput, scriptOnlyBlock, setDataAccess } from "../../safety/data-access.js";
9
15
  import { Type } from "typebox";
10
- import { appendApproval, approvalInputDigest, assertResearchDecision, bootstrapProject, ensureProjectBinding, hasCanonicalWorkspace, resolveResearchDecision, runInstitutionalFulltext, runLiteratureReview, runExpertReview, runAnalysisDelegation, runWritingReview, runMetaAnalysis, createStageRunner, exportAcademicDocument, recordCitationUse, runParallelPeerReview } from "../../index.js";
16
+ import { isUserSkillFile, skillCommandName, withResearchSkillNote } from "../../session/skill-reference.js";
17
+ import { markScriptOnly, parseSecretMarks, secretNote } from "../../safety/secret-marks.js";
18
+ import { appendApproval, approvalInputDigest, bootstrapProject, ensureProjectBinding, hasCanonicalWorkspace, runInstitutionalFulltext, runLiteratureReview, runExpertReview, runAnalysisDelegation, runWritingReview, runMetaAnalysis, createStageRunner, exportAcademicDocument, recordCitationUse, runParallelPeerReview } from "../../index.js";
11
19
  import { parseInitArgs } from "./init-args.js";
12
20
  import { runPlanWithPi } from "../../orchestration/pi-executor.js";
13
21
  import { formatEffects, hasElevatedEffects, normalizeEffects, toolsForEffects } from "../../orchestration/effects.js";
@@ -22,30 +30,38 @@ import { lstat, mkdir, readFile } from "node:fs/promises";
22
30
  import { PROVIDER_PRESETS, providerCredentialSource, saveProviderConfig } from "../../setup.js";
23
31
  import { dirname } from "node:path";
24
32
  import { fileURLToPath } from "node:url";
25
- import { coreSkillNames, enabledRecommendedSkillPaths, normalizeRecommendedSkillId, readRecommendationState, readRecommendedCatalog, recommendedSkillTarget, saveRecommendationState, setRecommendedSkillEnabled, validateModelInstalledRecommendedSkill, RecommendedSkillUnavailableError, } from "../../skills/recommended.js";
33
+ import { coreSkillNames, enabledRecommendedSkillPaths, normalizeRecommendedSkillId, readRecommendationState, readRecommendedCatalog, recommendedSkillTarget, saveRecommendationState, setRecommendedSkillEnabled, validateModelInstalledRecommendedSkill, RecommendedSkillUnavailableError } from "../../skills/recommended.js";
26
34
  import { buildRecommendedSkillInstallTask } from "../../skills/install-guidance.js";
27
35
  import { SkillManagerComponent } from "../../tui/skill-manager.js";
28
36
  import { BiosignalWizardComponent } from "../../tui/biosignal-wizard.js";
29
37
  import { readBiosignalPackCatalog, resolveBiosignalInstallPlan, } from "../../skills/biosignal-pack.js";
30
38
  import { WakeOptionsComponent } from "../../tui/wake-options.js";
31
- import { applyWakeVerifySync, buildWakePrompt, createWakeVerifyChecklist, formatWakeResult, labelsFor, waitForPanelWakeAnswer, } from "../../wake-options/runtime.js";
39
+ import { applyWakeVerifySync, buildWakePrompt, createWakeVerifyChecklist, formatWakeResult, labelsFor, waitForPanelWakeAnswer, recommendedOptionIndex, } from "../../wake-options/runtime.js";
32
40
  import { panelHub } from "../../panel/hub.js";
33
- import { appendChoiceRecord } from "../../research/choice.js";
41
+ import { formatMcpListing, unwrapMcpResult } from "../../integrations/mcp-format.js";
42
+ import { branchOf, findSkills, firstSentence, invokeSkill, readSkillSection, registrySkillListing, setSkillPathResolver, skillLoaded } from "../../session/skill-invoke.js";
43
+ import { formatDecisionsBrief, openDecisions, readDecisions, recordAsked, recordDeviation, recordSettled } from "../../research/decisions.js";
44
+ import { askedRows, checkProblems, PRACTICE_PATH, renderPractice, rowFor } from "../../research/practice.js";
45
+ import { confirmIntent, INTENT_FIELDS, intentBrief, quoted, readIntent, recordSaid, renderIntent, restateIntent } from "../../research/intent.js";
46
+ import { isPlanPointId, numberPoints, pointLabel, renderPlanMessage, settleFromReply } from "../../research/plan-message.js";
34
47
  import { enabledLocalSkillPaths, enabledLocalPromptPaths, readUserSkillState, scanLocalSkills, setLocalSkillEnabled, setLocalSkillsEnabled, skillNamesInPaths, userSkillId, } from "../../skills/user-skills.js";
35
48
  import { RuntimeMcpRegistry, setUserMcpConfigEnabled, } from "../../integrations/mcp-runtime.js";
36
49
  import { classifyIrreversibleHostCommand, extractToolCommandText, irreversibleHostBlockReason, } from "../../safety/irreversible-host-ops.js";
37
50
  import { SecretInputComponent, TextInputComponent, ProviderPickerComponent, } from "../../tui/provider-picker.js";
38
51
  import { resolveProviderBaseUrl } from "../../core/provider-endpoint.js";
39
- import { isArsPiActive, isArsPiTurn, psyclawArsPatch, setArsPiSessionActive, } from "../../ars/profile.js";
52
+ import { isArsPiActive, isArsPiTurn, psyclawArsPatch, setArsPiSessionActive } from "../../ars/profile.js";
40
53
  import { buildArsDoctorReport, ensurePdfEngineForExport } from "../../ars/doctor.js";
41
54
  import { formatAcademicSoftRouteInvocation, rankAcademicSoftRoutes, resolveAcademicSoftRoute, } from "../../ars/academic-router.js";
42
55
  import { advanceAnalysisPlan, createAnalysisPlan, formatAnalysisPlanStatus, readActiveAnalysisPlan, syncHandoffFromAnalysisPlan, writeAnalysisPlan, } from "../../analysis/plan.js";
43
- import { METHOD_TOPICS, mentionsLoadedSkill, methodTopicsIn } from "../../analysis/method-rules.js";
56
+ import { bundledCoreSkillsDir, METHOD_TOPICS, mentionsLoadedSkill, methodTopicsIn } from "../../analysis/method-rules.js";
57
+ import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
58
+ import { tmpdir } from "node:os";
59
+ import { validateAnalysisPlan } from "../../analysis/hooks.js";
44
60
  import { composeMethodInjection, injectedTopicsFor, readSkillPreferences, referencedDocumentTopics, refreshSkillResolution, SKILL_RESOLUTION_ENTRY, userSkillsOutsideScriptOnly, writeSkillPreferences, } from "../../analysis/skill-resolution.js";
45
61
  import { formatAnalysisPlanTakeover, resolveStatsIntent, } from "../../analysis/stats-router.js";
46
62
  import { arsRoot } from "../../ars/pi-panel-executor.js";
47
63
  import { ArsModeEditor, isArsModeEditorText } from "../../ars/mode-editor.js";
48
- import { MODE_STATUS, detectChatModeMismatch, formatChatModeMismatchNotice, nextSessionMode, parseSessionMode, sessionModePrompt, unattendedAnalysisPrompt, } from "../../session/modes.js";
64
+ import { MODE_STATUS, nextSessionMode, parseSessionMode, startingSessionMode, sessionModePrompt, unattendedAnalysisPrompt, } from "../../session/modes.js";
49
65
  import { continuouslyWorkWarningText, isContinuouslyWorkEnabled, } from "../../session/continuously-work.js";
50
66
  import { assertHumanVerifyGate, formatVerifyChecklist, isNaturalPlanConfirm, isPlanRitualConfirm, PLAN_RITUAL_PHRASE, ensureDefaultVerifyChecklist, loadVerifyChecklist, recordHumanVerification } from "../../verify/checklist.js";
51
67
  import { formatSessionHelp, formatSessionHelpBrief } from "../../session/help.js";
@@ -107,14 +123,6 @@ async function notifyAfterSkillChange(ctx, summary, level = "info") {
107
123
  }
108
124
  const activeAgentRuns = new Set();
109
125
  const CORE_SKILLS = new Set(["academic-grill", "research-intake", "evidence-capture", "citation-audit", "analysis-plan"]);
110
- function findLastMatching(items, predicate) {
111
- for (let index = items.length - 1; index >= 0; index -= 1) {
112
- const item = items[index];
113
- if (item !== undefined && predicate(item))
114
- return item;
115
- }
116
- return undefined;
117
- }
118
126
  function coreSkillPath(name) {
119
127
  return join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..", "skills", "core", name, "SKILL.md");
120
128
  }
@@ -284,7 +292,7 @@ function academicGrillRequest(subject, mode) {
284
292
  /** Lightweight ideation path for research directions. */
285
293
  function academicBrainstormRequest(subject) {
286
294
  return [
287
- "这是 /brainstorm:做选题向头脑风暴。不要加载 academic-grill,不要进入逐题压力测试或研究规格访谈。",
295
+ "这是 /ars brainstorm:做选题向头脑风暴。不要加载 academic-grill,不要进入逐题压力测试或研究规格访谈。",
288
296
  subject
289
297
  ? `头脑风暴主题:${subject}`
290
298
  : "根据当前对话与项目材料确定头脑风暴主题;已有信息不要重复询问。",
@@ -681,7 +689,7 @@ async function showAgentManager(ctx, statusOnly = false) {
681
689
  const rows = await agentManagerRows(ctx.cwd);
682
690
  if (!ctx.hasUI || typeof ctx.ui.custom !== "function" || statusOnly) {
683
691
  ctx.ui.notify(rows.map((row) => `${row.status === "core" ? "◆" : "●"} ${row.id} — ${row.name}(${row.stage})`).join("\n")
684
- || "暂无 Subagent。可用 /create-subagent 创建(类似 Claude Code)。", "info");
692
+ || "暂无 Subagent。可用 /create subagent 创建(类似 Claude Code)。", "info");
685
693
  return;
686
694
  }
687
695
  while (true) {
@@ -886,7 +894,7 @@ function modelBiosignalPackInstallTask(root, plan, skillRows, mcpRows, mcpPlans,
886
894
  `研究域:${plan.domainNames.join("、")}(${plan.domainIds.join(", ")})`,
887
895
  `当前项目:${root}`,
888
896
  `Skill 安装位置:${skillScopeLabel(skillScope)}。`,
889
- "用户已通过 /biosignal 向导明确授权本次打包安装。你可以直接联网、克隆或下载来源、使用所需包管理器安装依赖、执行安装命令,并写入与清单有关的项目或用户级配置;不要再次要求用户批准这些安装步骤。",
897
+ "用户已通过 /mcp biosignal 向导明确授权本次打包安装。你可以直接联网、克隆或下载来源、使用所需包管理器安装依赖、执行安装命令,并写入与清单有关的项目或用户级配置;不要再次要求用户批准这些安装步骤。",
890
898
  "不要写入 data/raw、.git、凭据或符号链接目标。不要把模型口头声称当作完成证据;每个条目安装后检查目标目录或 MCP 配置是否存在。",
891
899
  "",
892
900
  "MCP 清单:",
@@ -895,7 +903,7 @@ function modelBiosignalPackInstallTask(root, plan, skillRows, mcpRows, mcpPlans,
895
903
  "Skill 清单:",
896
904
  ...(skillLines.length > 0 ? skillLines : ["(无)"]),
897
905
  "",
898
- "目录中的版本、命令和依赖只作参考;请先阅读各来源仓库的实际安装说明再落地。各项已在推荐状态中默认启用;全部完成后执行 /reload,并提醒用户:Shift+Tab 切到 analysis,用自然语言描述数据与分析目标即可开始。",
906
+ "目录中的版本、命令和依赖只作参考;请先阅读各来源仓库的实际安装说明再落地。各项已在推荐状态中默认启用;全部完成后执行 /reload,并提醒用户:在研究模式里用自然语言描述数据与分析目标即可开始。",
899
907
  "若某一条目安装命令本身失败,直接诊断并修复;只有遇到必须由用户提供的凭据或外部软件许可证时才向用户说明。",
900
908
  ].join("\n");
901
909
  }
@@ -968,7 +976,7 @@ async function queueBiosignalPackInstall(pi, ctx, plan, runtime) {
968
976
  return;
969
977
  await markBiosignalPackDesired(ctx.cwd, plan, scope);
970
978
  queueHiddenInstallTask(pi, ctx, modelBiosignalPackInstallTask(ctx.cwd, plan, skillRows, selectedMcp, mcpCatalog.installPrep, scope));
971
- ctx.ui.notify("已将生理信号能力包安装任务交给当前模型(指令不展示在对话中)。完成后请执行 /reload,并 Shift+Tab 切到 analysis 使用。", "info");
979
+ ctx.ui.notify("已将生理信号能力包安装任务交给当前模型(指令不展示在对话中)。完成后请执行 /reload,并在研究模式里使用。", "info");
972
980
  }
973
981
  async function showBiosignalPack(pi, ctx, runtime) {
974
982
  const catalog = await readBiosignalPackCatalog();
@@ -976,7 +984,7 @@ async function showBiosignalPack(pi, ctx, runtime) {
976
984
  const lines = [
977
985
  "生理信号分析能力包(无交互 UI 时仅列出研究域):",
978
986
  ...catalog.domains.map((domain) => `- ${domain.id}: ${domain.name} — ${domain.description}`),
979
- "请在交互式终端运行 /biosignal 完成选型与安装。",
987
+ "请在交互式终端运行 /mcp biosignal 完成选型与安装。",
980
988
  ];
981
989
  ctx.ui.notify(lines.join("\n"), "info");
982
990
  return;
@@ -1186,31 +1194,140 @@ export default function psyclawExtension(pi) {
1186
1194
  void initNodeObservability();
1187
1195
  const developerCommands = process.env.PSYCLAW_DEVELOPER_COMMANDS === "1";
1188
1196
  const legacyTestApi = typeof pi.registerTool !== "function";
1197
+ if (!legacyTestApi) {
1198
+ // Every PsyClaw tool repairs badly serialised arguments before Pi validates them.
1199
+ const register = pi.registerTool.bind(pi);
1200
+ pi.registerTool = ((tool) => register(withArgRepair(tool)));
1201
+ // The built-in edit tool too: same tool, repaired arguments, run in the session's cwd.
1202
+ const editBase = createEditToolDefinition(process.cwd());
1203
+ pi.registerTool({
1204
+ ...editBase,
1205
+ async execute(toolCallId, input, signal, onUpdate, ctx) {
1206
+ return createEditToolDefinition(ctx.cwd).execute(toolCallId, input, signal, onUpdate, ctx);
1207
+ },
1208
+ });
1209
+ }
1189
1210
  const runtimeMcps = new RuntimeMcpRegistry();
1211
+ // Optional small decision model (PSYCLAW_DECIDER_URL); every use below falls back to the regex rule.
1212
+ const decider = new DecisionModel();
1213
+ // --- analysis (estimand) mode ------------------------------------------------------------
1214
+ const userTexts = (ctx) => {
1215
+ try {
1216
+ const branch = ctx.sessionManager?.getBranch?.() ?? [];
1217
+ return branch.map((entry) => {
1218
+ const m = entry.message;
1219
+ if (m?.role !== "user")
1220
+ return "";
1221
+ const c = m.content;
1222
+ return typeof c === "string" ? c : Array.isArray(c) ? c.map((x) => x.text ?? "").join("\n") : "";
1223
+ }).join("\n");
1224
+ }
1225
+ catch {
1226
+ return "";
1227
+ }
1228
+ };
1229
+ const estimandRqs = (cwd, ctx) => researchQuestionLabels(`${materialsText(cwd)}\n${userTexts(ctx)}`);
1230
+ const estimandReport = (cwd) => (existsSync(join(cwd, "results", "report.md")) ? "results/report.md" : "analysis/report.md");
1231
+ let estimandNudges = 0;
1232
+ let planSubmitTries = 0;
1233
+ let intentGateTries = 0;
1234
+ let practiceNudges = 0;
1235
+ let askGateTries = 0;
1236
+ let restateGateTries = 0;
1237
+ let estimandWorkStarted = false;
1238
+ // Skills seen in the last system prompt; psyclaw_skill finds and loads from it.
1239
+ let skillRegistry = [];
1240
+ // Research stage (analyst / writer) chosen by routing; it picks the research prompt section.
1241
+ const STAGE_ENTRY = "psyclaw-research-stage";
1242
+ const restoreStage = (sessionManager) => {
1243
+ try {
1244
+ const branch = sessionManager?.getBranch?.() ?? [];
1245
+ for (let i = branch.length - 1; i >= 0; i -= 1) {
1246
+ const entry = branch[i];
1247
+ if (entry?.type === "custom" && entry.customType === STAGE_ENTRY && (entry.data?.stage === "analysis" || entry.data?.stage === "writing"))
1248
+ return entry.data.stage;
1249
+ }
1250
+ }
1251
+ catch { /* no session yet */ }
1252
+ return undefined;
1253
+ };
1254
+ const setStage = (sessionManager, stage) => {
1255
+ if (restoreStage(sessionManager) === stage)
1256
+ return;
1257
+ try {
1258
+ pi.appendEntry(STAGE_ENTRY, { stage });
1259
+ }
1260
+ catch { /* session may not be open */ }
1261
+ };
1262
+ // Large skills load as a digest: find their SKILL.md from the registry, else the bundled packs.
1263
+ const bundledSkillFile = (name) => {
1264
+ try {
1265
+ const pkg = dirname(dirname(bundledCoreSkillsDir()));
1266
+ for (const dir of [join(pkg, "skills", "core"), join(pkg, "vendor", "ars"), join(pkg, "vendor", "nature-skills"), join(pkg, "vendor", "academic-paper-skills")]) {
1267
+ const candidate = join(dir, name, "SKILL.md");
1268
+ if (existsSync(candidate))
1269
+ return candidate;
1270
+ }
1271
+ }
1272
+ catch { /* package layout not found */ }
1273
+ return undefined;
1274
+ };
1275
+ setSkillPathResolver((name) => skillRegistry.find((skill) => skill.name === name)?.location ?? bundledSkillFile(name));
1276
+ const registry = (prompt) => {
1277
+ const listed = registrySkillListing(prompt);
1278
+ if (listed.skills.length)
1279
+ skillRegistry = listed.skills;
1280
+ return listed.systemPrompt;
1281
+ };
1190
1282
  let arsModeEditor;
1191
1283
  let arsUiContext;
1192
- let sessionMode = "chat";
1284
+ let sessionMode = startingSessionMode(false);
1285
+ let startingMode;
1193
1286
  // Sticky mode as persisted on the session branch. Headless runs have no mode editor, so the input
1194
1287
  // handler must read it here too; otherwise a restored analysis session is treated as chat.
1195
1288
  const restoreSessionMode = (sessionManager) => {
1196
1289
  const modeEntry = [...(sessionManager?.getBranch?.() ?? [])].reverse().find((entry) => entry.type === "custom" && entry.customType === "psyclaw-session-mode");
1197
1290
  return parseSessionMode(modeEntry?.data?.mode)
1198
- ?? (isArsPiActive(sessionManager) ? "academic" : sessionMode);
1291
+ ?? startingMode ?? sessionMode;
1199
1292
  };
1200
1293
  let turnStartedAt;
1201
1294
  let llmTurnSpan;
1202
1295
  let capturedTurnGeneration = false;
1296
+ // Tools only the research workflow uses; basic mode hides them (Pi's own tools, skills,
1297
+ // MCP and the choice box stay). Other active tools, such as ones added on the command line, are kept.
1298
+ // Tools each mode leaves out. basic: only Pi's tools, skills, MCP and the choice box. research: the
1299
+ // research workflow, no estimand tool. analysis (estimand): data tools and psyclaw_spec, no research
1300
+ // workflow tools. Other active tools, such as ones added on the command line, are kept.
1301
+ const MANAGED_TOOLS = ["psyclaw_workbench", "psyclaw_data_profile", "psyclaw_read_results", "psyclaw_recall_output", "psyclaw_plan", "psyclaw_cite", "psyclaw_ars_multi_agent", "psyclaw_ensure_pdf_engine", "psyclaw_spec", "psyclaw_intent"];
1302
+ const MODE_TOOLS = {
1303
+ basic: [],
1304
+ research: MANAGED_TOOLS.filter((name) => name !== "psyclaw_spec"),
1305
+ estimand: ["psyclaw_data_profile", "psyclaw_read_results", "psyclaw_recall_output", "psyclaw_spec"],
1306
+ };
1307
+ let managedAvailable;
1308
+ const syncModeTools = (mode) => {
1309
+ const api = pi;
1310
+ if (typeof api.getActiveTools !== "function" || typeof api.setActiveTools !== "function")
1311
+ return;
1312
+ try {
1313
+ const active = api.getActiveTools();
1314
+ managedAvailable ??= MANAGED_TOOLS.filter((name) => active.includes(name));
1315
+ const rest = active.filter((name) => !MANAGED_TOOLS.includes(name));
1316
+ const next = [...rest, ...managedAvailable.filter((name) => MODE_TOOLS[mode].includes(name))];
1317
+ if (next.length !== active.length || next.some((name) => !active.includes(name)))
1318
+ api.setActiveTools(next);
1319
+ }
1320
+ catch { /* session not ready: the next switch applies it */ }
1321
+ };
1203
1322
  const applySessionMode = (mode, opts) => {
1204
1323
  sessionMode = mode;
1324
+ syncModeTools(mode);
1205
1325
  arsModeEditor?.setMode(mode);
1206
1326
  arsUiContext?.ui.setStatus("mode", MODE_STATUS[mode]);
1207
1327
  // Clear legacy ars status key so it never duplicates with "mode".
1208
1328
  arsUiContext?.ui.setStatus("ars", undefined);
1209
1329
  if (opts?.syncSession === false || !arsUiContext)
1210
1330
  return;
1211
- setArsPiSessionActive(typeof pi.appendEntry === "function"
1212
- ? pi.appendEntry.bind(pi)
1213
- : undefined, mode === "academic");
1214
1331
  if (typeof pi.appendEntry === "function") {
1215
1332
  pi.appendEntry("psyclaw-session-mode", { mode });
1216
1333
  }
@@ -1218,11 +1335,11 @@ export default function psyclawExtension(pi) {
1218
1335
  const cycleSessionMode = () => {
1219
1336
  const next = nextSessionMode(arsModeEditor?.getMode() ?? sessionMode);
1220
1337
  applySessionMode(next);
1221
- arsUiContext?.ui.setStatus("mode", MODE_STATUS[next] ?? "chat");
1338
+ arsUiContext?.ui.setStatus("mode", MODE_STATUS[next]);
1222
1339
  };
1223
1340
  if (!legacyTestApi && typeof pi.registerShortcut === "function") {
1224
1341
  pi.registerShortcut("shift+tab", {
1225
- description: "Cycle chat → analysis → academic",
1342
+ description: "Switch between basic mode and research mode",
1226
1343
  handler: () => {
1227
1344
  cycleSessionMode();
1228
1345
  },
@@ -1284,6 +1401,34 @@ export default function psyclawExtension(pi) {
1284
1401
  });
1285
1402
  if (!legacyTestApi && typeof pi.on === "function")
1286
1403
  pi.on("agent_end", async (event, ctx) => {
1404
+ // Analysis mode end gate: once a specification exists, list what is missing (at most 6 times).
1405
+ try {
1406
+ if (restoreSessionMode(ctx?.sessionManager) === "estimand" && ctx?.cwd && (estimandWorkStarted || existsSync(join(ctx.cwd, SPEC_JSON))) && estimandNudges < 6) {
1407
+ const left = estimandGaps(ctx.cwd, loadSpec(ctx.cwd), estimandRqs(ctx.cwd, ctx), estimandReport(ctx.cwd));
1408
+ if (left.length) {
1409
+ estimandNudges += 1;
1410
+ pi.sendUserMessage(`[psyclaw] The analysis is not finished yet:\n- ${left.join("\n- ")}`, { deliverAs: "followUp" });
1411
+ }
1412
+ }
1413
+ }
1414
+ catch { /* the gate never blocks the turn's bookkeeping */ }
1415
+ // Research mode: a report without 做法对照 (or with one older than the decision record) gets a nudge, twice at most.
1416
+ try {
1417
+ if (restoreSessionMode(ctx?.sessionManager) === "research" && ctx?.cwd && practiceNudges < 2) {
1418
+ const plan = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
1419
+ const report = ["results/report.md", "analysis/report.md", "analysis/HANDOFF.md"].find((f) => existsSync(join(ctx.cwd, f)));
1420
+ if (plan && (plan.status === "running" || plan.status === "completed") && report) {
1421
+ const practice = join(ctx.cwd, PRACTICE_PATH);
1422
+ const record = join(ctx.cwd, ".psyclaw", "decisions.jsonl");
1423
+ const stale = existsSync(practice) && existsSync(record) && statSync(record).mtimeMs > statSync(practice).mtimeMs + 1000;
1424
+ if (!existsSync(practice) || stale) {
1425
+ practiceNudges += 1;
1426
+ pi.sendUserMessage(`[psyclaw] ${stale ? "做法对照 is older than the decision record" : `${report} has no 做法对照 yet`}: call psyclaw_plan action=compare with one check per item the researcher asked for, and put the section it returns at the top of ${report}.`, { deliverAs: "followUp" });
1427
+ }
1428
+ }
1429
+ }
1430
+ }
1431
+ catch { /* never blocks */ }
1287
1432
  const fallback = ctxProviderModel(ctx);
1288
1433
  finishAgentSpan(llmTurnSpan, piTurnSpanAttributes(fallback));
1289
1434
  llmTurnSpan = undefined;
@@ -1306,25 +1451,34 @@ export default function psyclawExtension(pi) {
1306
1451
  return { systemPrompt: `${event.systemPrompt}\n\n${prompt}` };
1307
1452
  });
1308
1453
  if (!legacyTestApi && typeof pi.on === "function")
1309
- pi.on("before_agent_start", (event, ctx) => {
1454
+ pi.on("before_agent_start", async (event, ctx) => {
1310
1455
  const restored = restoreSessionMode(ctx?.sessionManager);
1311
1456
  sessionMode = restored;
1312
- const modeBlock = restored === "analysis" && ctx && !ctx.hasUI
1313
- ? `${sessionModePrompt(restored)}\n\n${unattendedAnalysisPrompt()}`
1314
- : sessionModePrompt(restored);
1315
- if (restored === "academic" || isArsPiTurn(event.systemPrompt) || isArsPiActive(ctx?.sessionManager)) {
1457
+ syncModeTools(restored);
1458
+ let modeBlock = sessionModePrompt(restored, restored === "research" ? restoreStage(ctx?.sessionManager) : undefined);
1459
+ if (restored === "research" && ctx && !ctx.hasUI)
1460
+ modeBlock = `${modeBlock}\n\n${unattendedAnalysisPrompt()}`;
1461
+ if (isArsPiTurn(event.systemPrompt) || isArsPiActive(ctx?.sessionManager)) {
1316
1462
  return {
1317
- systemPrompt: `${event.systemPrompt}\n\n${modeBlock}\n\n${psyclawArsPatch({
1463
+ systemPrompt: `${registry(event.systemPrompt)}\n\n${modeBlock}\n\n${PSYCLAW_WRITING_RULES}\n\n${psyclawArsPatch({
1318
1464
  skills: event.systemPromptOptions?.skills,
1319
1465
  systemPrompt: event.systemPrompt,
1320
1466
  })}`,
1321
1467
  };
1322
1468
  }
1323
- return { systemPrompt: `${event.systemPrompt}\n\n${modeBlock}` };
1469
+ if (restored === "basic") {
1470
+ // Basic mode: Pi with a three-line prompt in place of the research identity prompt; skills by first sentence.
1471
+ return { systemPrompt: `${registry(event.systemPrompt.replace(PSYCLAW_IDENTITY_PROMPT, PSYCLAW_BASIC_PROMPT))}\n\n${modeBlock}` };
1472
+ }
1473
+ return { systemPrompt: `${registry(event.systemPrompt)}\n\n${modeBlock}` };
1324
1474
  });
1325
1475
  if (!legacyTestApi && typeof pi.on === "function")
1326
1476
  pi.on("session_start", async (_event, ctx) => {
1327
1477
  arsUiContext = ctx;
1478
+ if (typeof ctx.cwd === "string") {
1479
+ const hasWorkspace = await hasCanonicalWorkspace(ctx.cwd).catch(() => false) || Boolean(await readActiveProject(ctx.cwd).catch(() => undefined));
1480
+ startingMode = startingSessionMode(hasWorkspace);
1481
+ }
1328
1482
  if (typeof ctx.cwd === "string") {
1329
1483
  try {
1330
1484
  const discovered = await refreshSkillResolution(ctx.cwd);
@@ -1357,6 +1511,8 @@ export default function psyclawExtension(pi) {
1357
1511
  ctx.ui.setEditorComponent((tui, theme, keybindings) => {
1358
1512
  const editor = new ArsModeEditor(tui, theme, keybindings);
1359
1513
  arsModeEditor = editor;
1514
+ editor.cwd = ctx.cwd;
1515
+ void loadDataAccess(ctx.cwd).then((loaded) => { editor.secretEntries = loaded.entries; }).catch(() => undefined);
1360
1516
  editor.onModeChange = (mode) => {
1361
1517
  sessionMode = mode;
1362
1518
  ctx.ui.setStatus("mode", MODE_STATUS[mode]);
@@ -1367,7 +1523,7 @@ export default function psyclawExtension(pi) {
1367
1523
  };
1368
1524
  const modeEntry = [...ctx.sessionManager.getBranch()].reverse().find((entry) => entry.type === "custom" && entry.customType === "psyclaw-session-mode");
1369
1525
  const restore = parseSessionMode(modeEntry?.data?.mode)
1370
- ?? (isArsPiActive(ctx.sessionManager) ? "academic" : "chat");
1526
+ ?? startingMode ?? sessionMode;
1371
1527
  editor.setMode(restore);
1372
1528
  sessionMode = restore;
1373
1529
  ctx.ui.setStatus("mode", MODE_STATUS[restore]);
@@ -1375,6 +1531,31 @@ export default function psyclawExtension(pi) {
1375
1531
  return editor;
1376
1532
  });
1377
1533
  });
1534
+ const refreshEditorSecrets = async (cwd) => {
1535
+ if (!arsModeEditor)
1536
+ return;
1537
+ try {
1538
+ arsModeEditor.secretEntries = (await loadDataAccess(cwd)).entries;
1539
+ }
1540
+ catch { /* keep the old list */ }
1541
+ };
1542
+ // `@path:s` in a message marks that file script-only before anything else sees the message (secret-marks.ts).
1543
+ // Pi chains input handlers, so the main handler below receives the cleaned text.
1544
+ if (!legacyTestApi && typeof pi.on === "function")
1545
+ pi.on("input", async (event, ctx) => {
1546
+ if (event.source === "extension")
1547
+ return;
1548
+ const marks = parseSecretMarks(event.text);
1549
+ if (!marks.paths.length)
1550
+ return;
1551
+ const result = await markScriptOnly(ctx.cwd, marks.paths);
1552
+ if (result.marked.length)
1553
+ ctx.ui.notify(`已设为只许脚本读(模型不能读内容,分析脚本可以打开):${result.marked.join("、")}`, "info");
1554
+ for (const failed of result.failed)
1555
+ ctx.ui.notify(`没能标记 ${failed.path}:${failed.reason}`, "warning");
1556
+ await refreshEditorSecrets(ctx.cwd);
1557
+ return { action: "transform", text: result.marked.length ? `${marks.text}\n\n${secretNote(result.marked)}` : marks.text };
1558
+ });
1378
1559
  if (!legacyTestApi && typeof pi.on === "function")
1379
1560
  pi.on("input", async (event, ctx) => {
1380
1561
  if (event.source === "extension")
@@ -1401,14 +1582,26 @@ export default function psyclawExtension(pi) {
1401
1582
  }
1402
1583
  const mode = arsModeEditor?.getMode() ?? restoreSessionMode(ctx.sessionManager);
1403
1584
  const trimmed = event.text.trim();
1585
+ // Research mode: every message of the researcher goes into the intent record word for word (intent.ts),
1586
+ // before any routing, so the plan is checked against their words and a later session can read them back.
1587
+ if (mode === "research" && !trimmed.startsWith("/") && existsSync(join(ctx.cwd, ".psyclaw"))) {
1588
+ await recordSaid(ctx.cwd, event.text).catch(() => false);
1589
+ }
1590
+ // Research mode: a user-installed skill opened with /skill:<name> is reference material (skill-reference.ts).
1591
+ const named = mode === "research" ? skillCommandName(trimmed) : undefined;
1592
+ if (named) {
1593
+ const local = await enabledLocalSkillPaths(ctx.cwd, { excludedNames: coreSkillNames() }).catch(() => undefined);
1594
+ if (local?.loaded.some((skill) => skill.name === named))
1595
+ return { action: "transform", text: withResearchSkillNote(event.text) };
1596
+ }
1404
1597
  // A direct user statement is a valid human-review route when Panel is unavailable.
1405
1598
  // Do not infer approval from assistant output, quoted text, or a question about verification.
1406
1599
  if (/^我(?:已核验|已核实|已审阅并确认|核验了)(?:分析报告|论文定稿)?[。!!]?$/u.test(trimmed)) {
1407
1600
  const scope = trimmed.includes("论文定稿") ? "academic-finalize"
1408
1601
  : trimmed.includes("分析报告") ? "analysis-complete"
1409
- : mode === "academic" ? "academic-finalize" : mode === "analysis" ? "analysis-complete" : undefined;
1602
+ : "analysis-complete";
1410
1603
  if (!scope || !(await readActiveProject(ctx.cwd))) {
1411
- ctx.ui.notify("请先进入已初始化项目的 analysis 或 academic 模式,或明确说「我已核验分析报告」/「我已核验论文定稿」。", "warning");
1604
+ ctx.ui.notify("请先在已初始化的项目里操作,并明确说「我已核验分析报告」或「我已核验论文定稿」。", "warning");
1412
1605
  return { action: "handled" };
1413
1606
  }
1414
1607
  try {
@@ -1420,24 +1613,66 @@ export default function psyclawExtension(pi) {
1420
1613
  }
1421
1614
  return { action: "handled" };
1422
1615
  }
1423
- // Chat must not soft-takeover; when intent fits analysis/academic, remind only.
1424
- if (mode === "chat") {
1425
- const mismatch = detectChatModeMismatch(trimmed);
1426
- if (mismatch) {
1427
- ctx.ui.notify(mismatch.notify, "warning");
1616
+ // Plan confirmations (0.34): each card settles its own choice; once every choice is settled, a plain yes
1617
+ // (「可以」「批准」) or the old approval sentence approves the whole plan. No typed ritual is required.
1618
+ let approves = isPlanRitualConfirm(trimmed) || isNaturalPlanConfirm(trimmed);
1619
+ if (mode === "research" && decider.enabled && trimmed.length <= 400 && !isPlanRitualConfirm(trimmed)) {
1620
+ const pending = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
1621
+ if (pending && ["awaiting-confirm", "ready", "reviewing", "clarifying", "drafting"].includes(pending.status)) {
1622
+ const answers = await decider.ask("plan-approval", { reply: trimmed }, { meaning: APPROVAL_QUESTION });
1623
+ const meaning = DecisionModel.confident(answers?.meaning);
1624
+ if (meaning)
1625
+ approves = meaning === "approve";
1626
+ }
1627
+ }
1628
+ // A reply while the restated intent waits for the researcher: confirm it or restate again.
1629
+ if (mode === "research" && !trimmed.startsWith("/") && existsSync(join(ctx.cwd, ".psyclaw"))) {
1630
+ const intent = await readIntent(ctx.cwd).catch(() => undefined);
1631
+ if (intent?.current && !intent.current.confirmed) {
1632
+ return {
1633
+ action: "transform",
1634
+ text: [
1635
+ event.text,
1636
+ "",
1637
+ `[psyclaw] This is the researcher's reply to the restated intent (v${intent.current.version}). If it confirms it, call psyclaw_intent action=confirm with quote = the reply unchanged (and corrections = their corrections, if any, in their words). If it corrects or adds something substantial, restate again with psyclaw_intent action=restate, post the new message and wait. Do not submit the plan before the intent is confirmed.`,
1638
+ ].join("\n"),
1639
+ };
1640
+ }
1641
+ }
1642
+ // The researcher's reply to the numbered plan message settles every point at once (plan-message.ts).
1643
+ if (mode === "research" && !trimmed.startsWith("/")) {
1644
+ const pending = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
1645
+ const points = pending && ["awaiting-confirm", "ready", "reviewing"].includes(pending.status)
1646
+ ? (await openDecisions(ctx.cwd, pending.id)).filter((d) => isPlanPointId(d.id))
1647
+ : [];
1648
+ if (pending && points.length > 0) {
1428
1649
  return {
1429
1650
  action: "transform",
1430
- text: formatChatModeMismatchNotice(mismatch, trimmed),
1651
+ text: [
1652
+ event.text,
1653
+ "",
1654
+ `[psyclaw] This is the researcher's reply to the numbered plan (open: ${points.map((d) => pointLabel(d.id)).join(", ")}). Record it now with one psyclaw_plan action=answers call: quote = the reply unchanged; answers = one entry per point it names (option number, or text for their own approach); rest = recommended if it accepts the recommendations for the rest, else open; approved = ${approves ? "true (it reads as an approval)" : "true only if it approves the plan"}; additions = analyses it says are missing. Ask a psyclaw_ask card only for a point the reply leaves unclear.`,
1655
+ ].join("\n"),
1431
1656
  };
1432
1657
  }
1433
1658
  }
1434
- // Plan confirmations: soft「可以」= per-node / method acknowledge; ritual phrase = authorize execute.
1435
- if (mode === "analysis" && (isPlanRitualConfirm(trimmed) || isNaturalPlanConfirm(trimmed))) {
1659
+ if (mode === "research" && approves) {
1436
1660
  const plan = await readActiveAnalysisPlan(ctx.cwd);
1661
+ if (plan && (plan.status === "clarifying" || plan.status === "drafting")) {
1662
+ // A yes before the plan was submitted: nothing to approve yet.
1663
+ return {
1664
+ action: "transform",
1665
+ text: invokeSkill("analysis-plan", [
1666
+ `The researcher said "${trimmed}", but plan ${plan.id} has not been submitted yet (status: ${plan.status}).`,
1667
+ "Submit the proposal with psyclaw_plan action=submit, every decision point in decisions, and post the numbered message it returns. Do not run the confirmatory analysis yet.",
1668
+ ].join("\n"), skillLoaded(branchOf(ctx), "analysis-plan")),
1669
+ };
1670
+ }
1437
1671
  if (plan && (plan.status === "awaiting-confirm" || plan.status === "ready" || plan.status === "reviewing")) {
1438
1672
  const method = plan.confirmedMethod || plan.primaryAnalysis || plan.proposedMethods[0] || "按当前方案执行";
1439
- const pendingChoices = (plan.analysisChoices ?? []).filter((row) => !row.selected);
1440
- const ritual = isPlanRitualConfirm(trimmed);
1673
+ // Open questions come from the one decision record (psyclaw_ask / psyclaw_decide).
1674
+ const pendingChoices = await openDecisions(ctx.cwd, plan.id);
1675
+ const ritual = isPlanRitualConfirm(trimmed) || pendingChoices.length === 0;
1441
1676
  if (!ritual) {
1442
1677
  // Soft acknowledge only — never jump to run-now.
1443
1678
  let next = plan.status === "awaiting-confirm" && !plan.confirmedMethod
@@ -1445,33 +1680,29 @@ export default function psyclawExtension(pi) {
1445
1680
  : plan;
1446
1681
  next = await writeAnalysisPlan(ctx.cwd, next);
1447
1682
  const needChoices = pendingChoices.length > 0
1448
- ? `仍有 ${pendingChoices.length} 项子分析待选;请先逐项确认。`
1449
- : `方法已记下。要开始执行,请完整输入:「${PLAN_RITUAL_PHRASE}」`;
1450
- ctx.ui.notify(`${formatAnalysisPlanStatus(next)}\n${needChoices}`, "info");
1683
+ ? `仍有 ${pendingChoices.length} 项决定待定:${pendingChoices.map((d) => d.question).join(";")}。请先逐项确认。`
1684
+ : "方法已记下。";
1685
+ ctx.ui.notify(`${formatAnalysisPlanStatus(next, pendingChoices.length)}\n${needChoices}`, "info");
1451
1686
  return {
1452
1687
  action: "transform",
1453
- text: [
1454
- "/skill:analysis-plan",
1455
- "",
1688
+ text: invokeSkill("analysis-plan", [
1456
1689
  `User soft-acknowledged ("${trimmed}"). Do NOT run scripts yet.`,
1457
1690
  `Confirmed method so far: ${next.confirmedMethod ?? method}`,
1458
1691
  pendingChoices.length > 0
1459
- ? `Pending per-analysis choices: ${pendingChoices.map((row) => row.id).join(", ")}. Present the next undecided choice card and wait.`
1460
- : `All listed choices are decided (or none yet). Ask the user to type exactly: ${PLAN_RITUAL_PHRASE}`,
1461
- "Do not start /crosscheck or /verify until the user explicitly agrees to open that block.",
1462
- ].join("\n"),
1692
+ ? `Open decisions in the decision record: ${pendingChoices.map((d) => `${d.id} (${d.question})`).join(", ")}. Ask the next one with psyclaw_ask (same id) and wait; if the researcher already answered in text, record it with psyclaw_decide.`
1693
+ : "All listed choices are decided. Ask the user to approve the whole plan (a plain yes is enough).",
1694
+ "Do not start /check quick or /check full until the user explicitly agrees to open that block.",
1695
+ ].join("\n"), skillLoaded(branchOf(ctx), "analysis-plan")),
1463
1696
  };
1464
1697
  }
1465
1698
  if (pendingChoices.length > 0) {
1466
- ctx.ui.notify(`${formatAnalysisPlanStatus(plan)}\n仪式句已收到,但还有 ${pendingChoices.length} 项子分析未确认,请先逐项选完。`, "warning");
1699
+ ctx.ui.notify(`${formatAnalysisPlanStatus(plan, pendingChoices.length)}\n已收到批准,但还有 ${pendingChoices.length} 项决定待定,请先逐项定完。`, "warning");
1467
1700
  return {
1468
1701
  action: "transform",
1469
- text: [
1470
- "/skill:analysis-plan",
1471
- "",
1472
- `User typed the ritual phrase but ${pendingChoices.length} analysis choice(s) remain undecided.`,
1473
- "Present the next undecided choice card and wait. Do not execute.",
1474
- ].join("\n"),
1702
+ text: invokeSkill("analysis-plan", [
1703
+ `User approved the plan but ${pendingChoices.length} decision(s) are still open: ${pendingChoices.map((d) => `${d.id} (${d.question})`).join(", ")}.`,
1704
+ "Ask the next one with psyclaw_ask (same id) and wait. Do not execute.",
1705
+ ].join("\n"), skillLoaded(branchOf(ctx), "analysis-plan")),
1475
1706
  };
1476
1707
  }
1477
1708
  let next = plan.status === "awaiting-confirm"
@@ -1484,25 +1715,60 @@ export default function psyclawExtension(pi) {
1484
1715
  next = advanceAnalysisPlan(next, { type: "run-now" });
1485
1716
  next = await writeAnalysisPlan(ctx.cwd, next);
1486
1717
  if (next.status !== "running") {
1487
- ctx.ui.notify(`${formatAnalysisPlanStatus(next)}\n未能进入执行(检查子项确认与仪式批准)。`, "warning");
1718
+ ctx.ui.notify(`${formatAnalysisPlanStatus(next)}\n未能进入执行(检查子项是否都已确认)。`, "warning");
1488
1719
  return { action: "handled" };
1489
1720
  }
1490
- ctx.ui.notify(`${formatAnalysisPlanStatus(next)}\n已记录仪式批准并开始执行。`, "info");
1721
+ ctx.ui.notify(`${formatAnalysisPlanStatus(next)}\n已记录方案批准并开始执行。`, "info");
1491
1722
  return {
1492
1723
  action: "transform",
1493
- text: [
1494
- "/skill:analysis-plan",
1495
- "",
1496
- `User completed plan ritual ("${PLAN_RITUAL_PHRASE}"). Execute plan ${next.id} now.`,
1724
+ text: invokeSkill("analysis-plan", [
1725
+ `User approved the plan ("${trimmed}"). Execute plan ${next.id} now.`,
1497
1726
  `Confirmed method: ${next.confirmedMethod ?? method}`,
1498
- next.approvalMode === "auto" ? "approvalMode=auto: label outputs as 未经人审批." : "Human ritual approval recorded.",
1499
- "Do NOT auto-start /crosscheck or /verify. After scripts finish, ask whether to open those blocks; only proceed if the user agrees.",
1500
- ].join("\n"),
1727
+ next.approvalMode === "auto" ? "approvalMode=auto: label outputs as 未经人审批." : "Human plan approval recorded.",
1728
+ "Do NOT auto-start /check quick or /check full. After scripts finish, ask whether to open those blocks; only proceed if the user agrees.",
1729
+ ].join("\n"), skillLoaded(branchOf(ctx), "analysis-plan")),
1730
+ };
1731
+ }
1732
+ }
1733
+ if (mode !== "research")
1734
+ return;
1735
+ // Analysis first: a data-analysis request that also asks for figures or a write-up is still an
1736
+ // analysis (resolveStatsIntent already steps aside for writing-dominant requests such as 写论文).
1737
+ // The decision model routes when it is on and confident; otherwise the regex rules do.
1738
+ let routed;
1739
+ if (decider.enabled && !/^\//.test(trimmed)) {
1740
+ const answers = await decider.ask("route", { message: trimmed.slice(0, 6_000) }, { route: ROUTE_QUESTION, writing_skill: WRITING_SKILL_QUESTION });
1741
+ const route = DecisionModel.confident(answers?.route);
1742
+ if (route) {
1743
+ const skill = DecisionModel.confident(answers?.writing_skill, 0.6);
1744
+ routed = { route, ...(skill ? { skill } : {}) };
1745
+ }
1746
+ }
1747
+ const wantsStats = routed ? routed.route === "analysis" : Boolean(resolveStatsIntent(trimmed));
1748
+ const wantsAcademic = routed ? routed.route === "writing" : !wantsStats && Boolean(resolveAcademicSoftRoute(trimmed));
1749
+ if (mode === "research" && (wantsStats || wantsAcademic))
1750
+ setStage(ctx.sessionManager, wantsStats ? "analysis" : "writing");
1751
+ // No research question yet: start with academic-grill (brainstorm questions from the data, or grill
1752
+ // a rough idea) before any plan or writing.
1753
+ if (mode === "research" && trimmed.length <= 2_000) {
1754
+ let noQuestion = lacksResearchQuestion(trimmed);
1755
+ if (decider.enabled && (wantsStats || wantsAcademic || noQuestion)) {
1756
+ const answers = await decider.ask("has-question", { message: trimmed }, { has_question: HAS_QUESTION_QUESTION });
1757
+ const has = DecisionModel.yesNo(answers?.has_question);
1758
+ if (has !== undefined)
1759
+ noQuestion = !has;
1760
+ }
1761
+ if (noQuestion) {
1762
+ return {
1763
+ action: "transform",
1764
+ text: invokeSkill("academic-grill", [
1765
+ "The researcher has no research question yet. Follow academic-grill: look at the available data or materials once, then propose 2-4 answerable questions with psyclaw_ask (recommend one), or, if they already have a rough idea, grill it one point at a time. Do not build an analysis plan or write until a question is chosen.",
1766
+ "User request:",
1767
+ trimmed,
1768
+ ].join("\n"), skillLoaded(branchOf(ctx), "academic-grill")),
1501
1769
  };
1502
1770
  }
1503
1771
  }
1504
- const wantsStats = mode === "analysis" && Boolean(resolveStatsIntent(trimmed));
1505
- const wantsAcademic = mode === "academic" && Boolean(resolveAcademicSoftRoute(trimmed));
1506
1772
  if ((wantsStats || wantsAcademic) && !(await readActiveProject(ctx.cwd))) {
1507
1773
  if (await hasCanonicalWorkspace(ctx.cwd)) {
1508
1774
  // Heal binding silently — prior /init layout already present.
@@ -1512,36 +1778,44 @@ export default function psyclawExtension(pi) {
1512
1778
  return {
1513
1779
  action: "transform",
1514
1780
  text: [
1515
- "尚未 /init。请先提醒用户初始化工作区;若用户确认可无仓继续,再处理其请求。",
1781
+ "No PsyClaw workspace here yet. Handle the request; mention once that /init sets up the research folders.",
1516
1782
  "User request:",
1517
1783
  trimmed,
1518
1784
  ].join("\n"),
1519
1785
  };
1520
1786
  }
1521
1787
  else {
1522
- const choice = await ctx.ui.select("尚未 /init。统计/写作建议先建仓,否则交接与核对清单不完整。", ["先执行 /init", "本次继续(稍后 init)", "取消"], { timeout: 120_000 });
1523
- if (choice === "取消" || choice === undefined)
1788
+ const choice = await ctx.ui.select("这个文件夹还没有研究工作区。要在这里建立吗?(data/、analysis/、literature/、paper/,原始数据只读保护)", ["在这里建立(推荐)", "不建,直接继续", "取消"], { timeout: 120_000 });
1789
+ if (choice === "取消")
1524
1790
  return { action: "handled" };
1525
- if (choice === "先执行 /init") {
1526
- return { action: "transform", text: `/init\n\n(用户选择先初始化,完成后再继续:${trimmed})` };
1791
+ if (choice === "在这里建立(推荐)") {
1792
+ // Build it here, then carry on with this same request (no /init text sent to the model).
1793
+ const project = await bootstrapProject({ root: ctx.cwd });
1794
+ applySessionMode("research");
1795
+ ctx.ui.notify(`已建立研究工作区:${project.id}。继续处理你的请求。`, "info");
1527
1796
  }
1528
- ctx.ui.notify("继续本次请求;建议随后 /init。关键结果请做交叉核验。", "warning");
1797
+ else if (choice !== undefined)
1798
+ ctx.ui.notify("继续本次请求;需要时可以用 /init 建立工作区。", "info");
1529
1799
  }
1530
1800
  }
1531
- if (mode === "academic") {
1532
- const match = resolveAcademicSoftRoute(event.text);
1801
+ if (wantsAcademic) {
1802
+ const match = routed?.skill
1803
+ ? { skill: routed.skill, reason: "decision model", priority: 0 }
1804
+ : resolveAcademicSoftRoute(event.text) ?? (routed ? { skill: "academic-paper", reason: "decision model (writing)", priority: 0 } : null);
1533
1805
  if (!match)
1534
1806
  return;
1535
1807
  const ranked = rankAcademicSoftRoutes(event.text, 3);
1536
1808
  return {
1537
1809
  action: "transform",
1538
- text: formatAcademicSoftRouteInvocation(match, event.text, ranked.slice(1)),
1810
+ text: formatAcademicSoftRouteInvocation(match, event.text, ranked.slice(1), { skillLoaded: skillLoaded(branchOf(ctx), match.skill) }),
1539
1811
  };
1540
1812
  }
1541
- if (mode === "analysis") {
1813
+ {
1542
1814
  const userSkills = await userSkillsOutsideScriptOnly(ctx.cwd).catch(() => []);
1543
1815
  const userSkillNames = userSkills.map((skill) => skill.name);
1544
- const match = resolveStatsIntent(event.text, { userSkillNames });
1816
+ const match = routed
1817
+ ? (routed.route === "analysis" ? { kind: "stats-analysis", reason: "decision model", topics: methodTopicsIn(event.text) } : null)
1818
+ : resolveStatsIntent(event.text, { userSkillNames });
1545
1819
  const namesUserSkill = mentionsLoadedSkill(event.text, userSkillNames);
1546
1820
  // The task often lives in a document the message names ("Read BRIEF.md"), not in the message itself.
1547
1821
  const documents = namesUserSkill
@@ -1579,7 +1853,20 @@ export default function psyclawExtension(pi) {
1579
1853
  }
1580
1854
  catch { /* the process takeover still applies */ }
1581
1855
  if (match) {
1582
- return { action: "transform", text: formatAnalysisPlanTakeover(event.text, block || undefined) };
1856
+ // Research mode: the takeover opens a plan in code, so approval and the run gate apply.
1857
+ let planLine = "";
1858
+ if (await readActiveProject(ctx.cwd).catch(() => null)) {
1859
+ const active = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
1860
+ if (!active || active.status === "completed") {
1861
+ const created = await writeAnalysisPlan(ctx.cwd, createAnalysisPlan({ goal: event.text.trim().slice(0, 300) }));
1862
+ planLine = `Plan ${created.id} is open for this request.`;
1863
+ }
1864
+ else {
1865
+ planLine = `Plan ${active.id} is open (status: ${active.status}).`;
1866
+ }
1867
+ }
1868
+ const takeover = formatAnalysisPlanTakeover(event.text, block || undefined, { skillLoaded: skillLoaded(branchOf(ctx), "analysis-plan") });
1869
+ return { action: "transform", text: planLine ? `${takeover}\n\n${planLine}` : takeover };
1583
1870
  }
1584
1871
  if (block)
1585
1872
  return { action: "transform", text: `${event.text.trim()}\n\n${block}` };
@@ -1588,13 +1875,146 @@ export default function psyclawExtension(pi) {
1588
1875
  });
1589
1876
  if (!legacyTestApi && typeof pi.on === "function")
1590
1877
  pi.on("context", (event) => {
1591
- const messages = maskToolObservationsStable(event.messages);
1878
+ const messages = maskHeavyParts(maskToolObservationsStable(event.messages));
1592
1879
  if (messages === event.messages)
1593
1880
  return;
1594
1881
  return { messages };
1595
1882
  });
1596
1883
  let dataAccessWarningShown = false;
1597
1884
  const shellClock = new ShellClock();
1885
+ // Research mode: running a project script waits for plan approval. Exploration scripts
1886
+ // (explore/eda/profile/check/inspect/codebook in the name) still run; unattended runs are not gated.
1887
+ /** Approve the active plan from an approval card: same steps as a typed yes. Returns the new status. */
1888
+ async function approvePlanFromCard(cwd) {
1889
+ const plan = await readActiveAnalysisPlan(cwd).catch(() => null);
1890
+ if (!plan || !["awaiting-confirm", "ready", "reviewing"].includes(plan.status))
1891
+ return undefined;
1892
+ if ((await openDecisions(cwd, plan.id)).length > 0)
1893
+ return undefined;
1894
+ const method = plan.confirmedMethod || plan.primaryAnalysis || plan.proposedMethods[0] || "按当前方案执行";
1895
+ let next = plan.status === "awaiting-confirm" ? advanceAnalysisPlan(plan, { type: "confirm", method, backend: "local-script" }) : plan;
1896
+ next = advanceAnalysisPlan(next, { type: "ritual-approve", text: PLAN_RITUAL_PHRASE });
1897
+ if (next.status === "reviewing" || next.status === "awaiting-confirm")
1898
+ next = advanceAnalysisPlan(next, { type: "review" });
1899
+ next = advanceAnalysisPlan(next, { type: "run-now" });
1900
+ next = await writeAnalysisPlan(cwd, next);
1901
+ return next.status;
1902
+ }
1903
+ async function confirmatoryRunGate(ctx, script) {
1904
+ const mode = ctx.sessionManager ? restoreSessionMode(ctx.sessionManager) : sessionMode;
1905
+ if (mode !== "research" || ctx.hasUI !== true)
1906
+ return undefined;
1907
+ if (/explor|eda|profile|check|inspect|codebook/i.test(script))
1908
+ return undefined;
1909
+ const plan = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
1910
+ if (!plan || plan.status === "running" || plan.status === "completed" || (plan.approvalMode ?? "human") === "auto")
1911
+ return undefined;
1912
+ const open = await openDecisions(ctx.cwd, plan.id);
1913
+ return [
1914
+ `方案 ${plan.id} 还没批准(状态:${plan.status}),${script} 这类正式分析脚本先不跑。`,
1915
+ plan.status === "clarifying" || plan.status === "drafting"
1916
+ ? "先用 psyclaw_plan action=submit 提交方案(主要结果、主分析、缺失值、多重比较、排除标准)。"
1917
+ : "",
1918
+ open.length ? `还有 ${open.length} 项决定待定:${open.map((d) => `${d.id}(${d.question})`).join(";")},用 psyclaw_ask 问研究者。` : "",
1919
+ "全部定好后请研究者回复「可以」批准方案。探索性脚本(文件名含 explore、eda、profile、check、inspect)可以照常跑。",
1920
+ ].filter(Boolean).join("\n");
1921
+ }
1922
+ const scriptRuns = new Set(); // tool calls that ran a project script, for the decision-points notice
1923
+ const packageNet = new PackageNet();
1924
+ const installNotes = new Map();
1925
+ const installsRunning = new Map(); // package set -> log path
1926
+ // R (CRAN) and conda installs: same idea as pip/uv, the fastest route for this command only.
1927
+ const speedCache = new Map();
1928
+ const bestRoute = async (key, targets) => {
1929
+ const hit = speedCache.get(key);
1930
+ if (hit && Date.now() - hit.at < 30 * 60_000)
1931
+ return hit.best;
1932
+ const best = fastest(await probeSpeeds(targets).catch(() => []));
1933
+ speedCache.set(key, { at: Date.now(), best });
1934
+ return best;
1935
+ };
1936
+ async function routeOtherInstall(ctx, toolCallId, input, command) {
1937
+ if (typeof input.command !== "string")
1938
+ return;
1939
+ if (isRInstall(command)) {
1940
+ ctx.ui.notify("装包前测速:CRAN 和国内镜像…", "info");
1941
+ const best = await bestRoute("cran", cranTargets());
1942
+ if (!best || /cloud\.r-project\.org/.test(best.base) && !best.direct)
1943
+ return;
1944
+ const profile = join(tmpdir(), `psyclaw-cran-${best.base.replace(/[^a-z0-9]+/gi, "_")}.R`);
1945
+ writeFileSync(profile, cranProfile(best.base), "utf8");
1946
+ input.command = routeRCommand(command, best, profile);
1947
+ installNotes.set(toolCallId, `[psyclaw] 这次 R 装包走的是 ${best.route}(${best.base},实测 ${best.kb_s} KB/s;只对这条命令生效,你的 .Rprofile 照常读取)。`);
1948
+ return;
1949
+ }
1950
+ const channels = condaChannels(command);
1951
+ if (channels.length) {
1952
+ ctx.ui.notify("装包前测速:conda 频道和国内镜像…", "info");
1953
+ const best = await bestRoute(`conda:${channels[0]}`, condaTargets(channels[0]));
1954
+ if (!best || /anaconda\.org/.test(best.base) && !best.direct)
1955
+ return;
1956
+ input.command = /anaconda\.org/.test(best.base) ? `unset HTTPS_PROXY HTTP_PROXY https_proxy http_proxy ALL_PROXY all_proxy; ${command}` : routeCondaCommand(command, best);
1957
+ installNotes.set(toolCallId, `[psyclaw] 这次 conda 装包走的是 ${best.route}(实测 ${best.kb_s} KB/s;只对这条命令生效,频道不变)。`);
1958
+ }
1959
+ }
1960
+ // Package installs: measure PyPI and mirrors once, run this command through the fastest route,
1961
+ // and ask the researcher first when it would still be slow. No global pip/uv config is written.
1962
+ async function routePackageInstall(ctx, toolCallId, input, command, install) {
1963
+ if (typeof input.command !== "string")
1964
+ return undefined;
1965
+ const names = install.packages.join(" ") || "(包名未解析)";
1966
+ const key = [...install.packages].sort().join(" ");
1967
+ const running = key ? installsRunning.get(key) : undefined;
1968
+ if (running) {
1969
+ input.command = `echo ${shellQuote(`[psyclaw] ${names} 已在后台安装中(日志 ${running})。装完会自动通知你;先做不依赖它们的工作,不要重复安装,也不要 sleep 等待。`)}`;
1970
+ return undefined;
1971
+ }
1972
+ ctx.ui.notify("装包前测速:PyPI 和国内镜像…", "info");
1973
+ const report = await packageNet.check(install).catch(() => undefined);
1974
+ if (!report)
1975
+ return undefined;
1976
+ if (!report.best) {
1977
+ return { block: true, reason: `[psyclaw] 装包前测速:PyPI 和镜像都连不上(${names})。不要重试;告诉研究者,或用已有的退回方案继续。` };
1978
+ }
1979
+ const routed = routeCommand(command, report.best);
1980
+ if (report.ask_researcher_first && ctx.hasUI) {
1981
+ const now = `现在装(${describeRoute(report)})`;
1982
+ const skip = "跳过,用退回方案";
1983
+ const later = "我以后自己装";
1984
+ const choice = await ctx.ui.select(`装包前确认:${names}`, [now, skip, later], { timeout: 120_000 });
1985
+ if (choice === skip) {
1986
+ return { block: true, reason: `[psyclaw] 研究者选择不装 ${names}。不要再尝试安装;用退回方案继续,并在小结里说明。` };
1987
+ }
1988
+ if (choice === later) {
1989
+ return { block: true, reason: `[psyclaw] 研究者会以后自己装 ${names}。不要再尝试安装;把这条命令写进小结:${routed}` };
1990
+ }
1991
+ }
1992
+ if (ctx.hasUI && key && (report.best.minutes ?? 0) >= backgroundInstallMinutes()) {
1993
+ const log = join(ctx.cwd, ".psyclaw", "installs", `${toolCallId.replace(/[^\w-]/g, "_")}.log`);
1994
+ installsRunning.set(key, log);
1995
+ const route = describeRoute(report);
1996
+ startBackgroundInstall(routed, ctx.cwd, log, (result) => {
1997
+ installsRunning.delete(key);
1998
+ const ok = result.code === 0;
1999
+ const text = ok
2000
+ ? `[psyclaw] 后台安装完成:${names}(${route},用时 ${result.seconds} 秒)。现在可以使用这些包;先导入一次确认。`
2001
+ : `[psyclaw] 后台安装失败:${names}(退出码 ${result.code ?? "无"},用时 ${result.seconds} 秒)。日志末尾:\n${result.tail}\n不要原样重试;告诉研究者,或用退回方案继续。`;
2002
+ ctx.ui.notify(ok ? `后台安装完成:${names}` : `后台安装失败:${names}`, ok ? "info" : "warning");
2003
+ try {
2004
+ pi.sendMessage({ customType: "psyclaw-install-done", content: text, display: true }, ctx.isIdle() ? { triggerTurn: true } : { deliverAs: "steer" });
2005
+ }
2006
+ catch { /* session closed: the notify above is enough */ }
2007
+ });
2008
+ input.command = `echo ${shellQuote(`[psyclaw] 已在后台开始安装 ${names}(${route},只对这条命令生效;日志 ${log})。装完会自动通知你。在那之前先做不依赖这些包的工作;不要 sleep 等待,不要重复安装,也不要导入它们。`)}`;
2009
+ return undefined;
2010
+ }
2011
+ input.command = routed;
2012
+ const seconds = installTimeoutSeconds(report.best.minutes);
2013
+ if (seconds !== undefined)
2014
+ input.timeout = Math.max(typeof input.timeout === "number" ? input.timeout : 0, seconds);
2015
+ installNotes.set(toolCallId, `[psyclaw] 这次装包走的是 ${describeRoute(report)}(只对这条命令生效)。`);
2016
+ return undefined;
2017
+ }
1598
2018
  if (!legacyTestApi && typeof pi.on === "function")
1599
2019
  pi.on("tool_call", async (event, ctx) => {
1600
2020
  // Host-teardown hard block runs even without /init — project approvals do not cover this.
@@ -1607,8 +2027,46 @@ export default function psyclawExtension(pi) {
1607
2027
  return { block: true, terminate: true, reason };
1608
2028
  }
1609
2029
  }
2030
+ const placeholder = maskedPlaceholderReason(event.toolName, event.input);
2031
+ if (placeholder)
2032
+ return { block: true, reason: placeholder };
2033
+ // analysis/spec.json and spec.md are written by code only (psyclaw_spec).
2034
+ const specPath = /analysis\/spec\.(json|md)/;
2035
+ const writesSpec = (event.toolName === "write" || event.toolName === "edit")
2036
+ ? specPath.test(String(event.input?.path ?? ""))
2037
+ : event.toolName === "bash" && specPath.test(commandText ?? "") && /(>|\btee\b|\bsed\s+-i|\bmv\b|\bcp\b|\brm\b|open\([^)]*["']w)/.test(commandText ?? "");
2038
+ if (writesSpec)
2039
+ return { block: true, reason: `${SPEC_JSON} and ${SPEC_MD} are written by code; use psyclaw_spec.` };
2040
+ moveTimeoutPrefix(event.toolName, event.input);
1610
2041
  applyShellTimeout(event.toolName, event.input);
2042
+ const script = event.toolName === "bash" && commandText ? scriptInCommand(commandText) : undefined;
2043
+ const currentMode = restoreSessionMode(ctx.sessionManager);
2044
+ if (currentMode === "estimand" && ["bash", "write", "edit"].includes(event.toolName))
2045
+ estimandWorkStarted = true;
2046
+ if (script) {
2047
+ const refusal = await confirmatoryRunGate(ctx, script);
2048
+ if (refusal)
2049
+ return { block: true, reason: refusal };
2050
+ // Analysis mode: analysis scripts wait until at least one estimand is confirmed (exploration still runs).
2051
+ if (currentMode === "estimand" && !/explor|eda|profile|check|inspect|codebook/i.test(script)) {
2052
+ const spec = loadSpec(ctx.cwd);
2053
+ const confirmed = spec ? Object.values(spec.estimands).some((e) => e.confirmed_at) : false;
2054
+ if (!confirmed) {
2055
+ return { block: true, reason: `[psyclaw] Analysis mode: write the estimands with psyclaw_spec action=write and confirm them with action=confirm before running analysis scripts such as ${script}. Exploration scripts (explore, eda, profile, check in the name) can run now.` };
2056
+ }
2057
+ }
2058
+ scriptRuns.add(event.toolCallId);
2059
+ }
1611
2060
  shellClock.start(event.toolName, event.toolCallId, commandText);
2061
+ const install = event.toolName === "bash" && commandText ? parsePipInstall(commandText) : undefined;
2062
+ if (install && commandText) {
2063
+ const routed = await routePackageInstall(ctx, event.toolCallId, event.input, commandText, install);
2064
+ if (routed)
2065
+ return routed;
2066
+ }
2067
+ else if (event.toolName === "bash" && commandText) {
2068
+ await routeOtherInstall(ctx, event.toolCallId, event.input, commandText);
2069
+ }
1612
2070
  try {
1613
2071
  const access = await loadDataAccess(ctx.cwd);
1614
2072
  if (access.warning && !dataAccessWarningShown) {
@@ -1673,10 +2131,14 @@ export default function psyclawExtension(pi) {
1673
2131
  const timedOutIndex = content.findIndex((part) => part.type === "text" && isShellTimeout(event.toolName, part.text));
1674
2132
  const timedOut = content[timedOutIndex];
1675
2133
  if (timedOut?.type === "text") {
1676
- content[timedOutIndex] = { ...timedOut, text: `${timedOut.text}\n${SHELL_TIMEOUT_HINT}` };
2134
+ content[timedOutIndex] = { ...timedOut, text: `${timedOut.text}\n${shellClock.timeoutHint(event.toolCallId)}` };
1677
2135
  changed = true;
1678
2136
  }
1679
- const timing = shellClock.finish(event.toolCallId);
2137
+ const installNote = installNotes.get(event.toolCallId);
2138
+ installNotes.delete(event.toolCallId);
2139
+ const ranScript = scriptRuns.delete(event.toolCallId);
2140
+ const decisionNote = ranScript ? await decisionPointsNotice(ctx.cwd).catch(() => undefined) : undefined;
2141
+ const timing = [installNote, shellClock.finish(event.toolCallId), decisionNote, shellClock.budgetNote()].filter(Boolean).join("\n") || undefined;
1680
2142
  const lastText = content.map((part) => part.type).lastIndexOf("text");
1681
2143
  const last = content[lastText];
1682
2144
  if (timing && last?.type === "text") {
@@ -1698,6 +2160,19 @@ export default function psyclawExtension(pi) {
1698
2160
  }
1699
2161
  }
1700
2162
  }
2163
+ // Research mode: reading a user-installed skill's SKILL.md gets the reference-material note.
2164
+ if (sessionMode === "research" && event.toolName === "read" && !event.isError) {
2165
+ const path = String(event.input?.path ?? "");
2166
+ if (/SKILL\.md$/i.test(path)) {
2167
+ const local = await enabledLocalSkillPaths(ctx.cwd, { excludedNames: coreSkillNames() }).catch(() => undefined);
2168
+ const at = content.map((part) => part.type).lastIndexOf("text");
2169
+ const part = content[at];
2170
+ if (local && isUserSkillFile(ctx.cwd, path, local.paths) && part?.type === "text") {
2171
+ content[at] = { ...part, text: withResearchSkillNote(part.text) };
2172
+ changed = true;
2173
+ }
2174
+ }
2175
+ }
1701
2176
  if (!changed)
1702
2177
  return;
1703
2178
  return { content };
@@ -1728,21 +2203,23 @@ export default function psyclawExtension(pi) {
1728
2203
  ...(parsed.goal === undefined ? {} : { goal: parsed.goal }),
1729
2204
  ...(parsed.paradigm === undefined ? {} : { paradigm: parsed.paradigm }),
1730
2205
  });
2206
+ applySessionMode("research");
1731
2207
  if (already || hadProject) {
1732
2208
  ctx.ui.notify([
1733
2209
  `已检测到既有工作区,无需重新建仓:${project.id}`,
1734
- "规范目录与 psyclaw.md 已存在;跨会话可直接继续 analysis / academic。",
1735
- "Shift+Tab:chat → analysis → academic · 输入 /help 查看速览。",
2210
+ "规范目录与 psyclaw.md 已存在;跨会话可直接继续分析或写作。",
2211
+ "还没想好研究问题?/ars brainstorm 一起想问题;/ars grill 把想法逐条问清楚。",
2212
+ "当前为研究模式;Shift+Tab 切换基础模式 / 研究模式。输入 /help 查看速览。",
1736
2213
  ].join("\n"), "info");
1737
2214
  return;
1738
2215
  }
1739
2216
  ctx.ui.notify([
1740
2217
  `工作仓库已初始化:${project.id}`,
1741
2218
  "已创建 data/raw|clean|secret、analysis/、literature/、paper/、psyclaw.md、.psyclaw/",
1742
- "data/secret 默认 script-only:模型不能直接读内容,分析脚本可以打开。/data-access 可改级别或指定其他文件。",
1743
- "Shift+Tab:chat → analysis → academic",
1744
- "Thinking:Ctrl+Shift+T",
1745
- "澄清与分析请切到 analysis;写作审稿请切到 academic。输入 /help 查看速览。",
2219
+ "data/secret 默认 script-only:模型不能直接读内容,分析脚本可以打开。/secret 可改级别或指定其他文件。",
2220
+ "研究模式:分析、写作、审稿都在同一个对话里,按你说的事走对应流程。",
2221
+ "还没想好研究问题?/ars brainstorm 从数据里一起想几个可做的问题;/ars grill 把一个初步想法逐条问清楚。直接说“想用这份数据写文章”也会先走这一步。",
2222
+ "Shift+Tab:基础模式 / 研究模式 · Thinking:Ctrl+Shift+T · /help 查看速览。",
1746
2223
  ].join("\n"), "info");
1747
2224
  }
1748
2225
  catch (error) {
@@ -1750,23 +2227,40 @@ export default function psyclawExtension(pi) {
1750
2227
  }
1751
2228
  },
1752
2229
  });
1753
- pi.registerCommand("data-access", {
1754
- description: "查看或设置文件展示级别(full 或 script-only)",
2230
+ pi.registerCommand("secret", {
2231
+ description: "数据文件只许脚本读:/secret <文件> 设置,/secret off <文件> 取消,/secret list 查看全部;消息里写 @文件:s 也可以",
1755
2232
  handler: async (args, ctx) => {
1756
2233
  try {
1757
2234
  const parts = args.trim().split(/\s+/).filter(Boolean);
1758
2235
  if (parts.length === 0) {
2236
+ const loaded = await loadDataAccess(ctx.cwd);
2237
+ const secret = loaded.entries.filter((entry) => entry.access === "script-only").map((entry) => entry.path);
2238
+ ctx.ui.notify([`只许脚本读的文件:${secret.join("、") || "无"}`, "设置:/secret <文件>;取消:/secret off <文件>;全部访问级别:/secret list;消息里写 @文件:s 也可以。", loaded.warning].filter(Boolean).join("\n"), loaded.warning ? "warning" : "info");
2239
+ return;
2240
+ }
2241
+ if (parts[0] === "list" && parts.length === 1) {
1759
2242
  const loaded = await loadDataAccess(ctx.cwd);
1760
2243
  ctx.ui.notify([formatDataAccess(loaded.entries), loaded.warning].filter(Boolean).join("\n"), loaded.warning ? "warning" : "info");
1761
2244
  return;
1762
2245
  }
1763
- const access = parts.at(-1);
1764
- if (parts[0] !== "set" || parts.length < 3 || (access !== "full" && access !== "script-only")) {
1765
- ctx.ui.notify("用法:/data-access 或 /data-access set <相对路径> <full|script-only>", "error");
2246
+ if (parts[0] === "off" || parts[0] === "full") {
2247
+ const targets = parts.slice(1).map((p) => p.replace(/^@/, "").replace(/:s$/, ""));
2248
+ if (!targets.length) {
2249
+ ctx.ui.notify("用法:/secret off <文件>", "error");
2250
+ return;
2251
+ }
2252
+ for (const target of targets)
2253
+ await setDataAccess(ctx.cwd, target, "full");
2254
+ await refreshEditorSecrets(ctx.cwd);
2255
+ ctx.ui.notify(`已取消只许脚本读:${targets.join("、")}`, "info");
1766
2256
  return;
1767
2257
  }
1768
- const entries = await setDataAccess(ctx.cwd, parts.slice(1, -1).join(" "), access);
1769
- ctx.ui.notify(formatDataAccess(entries), "info");
2258
+ const result = await markScriptOnly(ctx.cwd, parts.map((p) => p.replace(/^@/, "").replace(/:s$/, "")));
2259
+ await refreshEditorSecrets(ctx.cwd);
2260
+ if (result.marked.length)
2261
+ ctx.ui.notify(`已设为只许脚本读:${result.marked.join("、")}`, "info");
2262
+ for (const failed of result.failed)
2263
+ ctx.ui.notify(`没能标记 ${failed.path}:${failed.reason}`, "warning");
1770
2264
  }
1771
2265
  catch (error) {
1772
2266
  await notifyError(ctx, error);
@@ -1780,13 +2274,14 @@ export default function psyclawExtension(pi) {
1780
2274
  if (!focus) {
1781
2275
  ctx.ui.notify([
1782
2276
  formatVerifyChecklist(await loadVerifyChecklist(ctx.cwd)),
1783
- "/crosscheck:过程性核对(数据、引文是否真实存在、格式/报告要求等)。",
1784
- "人审不经斜杠命令:收尾门禁会要求 Panel「核实」或唤醒选项。",
2277
+ "/check quick <焦点>:过程核对(数据、引文是否真实存在、格式/报告要求等)。",
2278
+ "/check full <焦点>:整体验证(分析结果是否成立、引文是否合理、方法是否合理)。",
2279
+ "人审不经斜杠命令:收尾门禁会要求 Panel「核实」或选择框。",
1785
2280
  ].join("\n"), "info");
1786
2281
  return;
1787
2282
  }
1788
2283
  pi.sendUserMessage([
1789
- "/crosscheck — 过程性交叉核对(AI)。",
2284
+ "/check quick — 过程性交叉核对(AI)。",
1790
2285
  `焦点:${focus}`,
1791
2286
  "范围重点:",
1792
2287
  "1) 数据与表:字段、N、表内数值与脚本/输出是否过程一致;",
@@ -1794,9 +2289,9 @@ export default function psyclawExtension(pi) {
1794
2289
  "3) 格式与报告要求:APA/三线表/必备报告字段、清单项是否齐;",
1795
2290
  "4) 过程产物:脚本入口、中间文件、可复现痕迹是否齐全。",
1796
2291
  "执行方式:派出至少两个独立审查视角(例如:数据一致性;引文存在性;格式/报告合同),各自给出发现后再合并为一份报告;标出一致项与冲突项。",
1797
- "不得自称已过人审。不要在用户未明确同意前自动启动本核对。人审由系统在交接/定稿门禁自动要求,经 Panel「核实」或唤醒选项完成。",
2292
+ "不得自称已过人审。不要在用户未明确同意前自动启动本核对。人审由系统在交接/定稿门禁自动要求,经 Panel「核实」或选择框完成。",
1798
2293
  ].join("\n"), ctx.isIdle() ? {} : { deliverAs: "followUp" });
1799
- ctx.ui.notify(`已启动过程性 /crosscheck(焦点:${focus})。大段核对应先征得用户同意。`, "info");
2294
+ ctx.ui.notify(`已启动过程核对 /check quick(焦点:${focus})。大段核对应先征得用户同意。`, "info");
1800
2295
  }
1801
2296
  catch (error) {
1802
2297
  await notifyError(ctx, error);
@@ -1809,13 +2304,13 @@ export default function psyclawExtension(pi) {
1809
2304
  if (!focus) {
1810
2305
  ctx.ui.notify([
1811
2306
  formatVerifyChecklist(await loadVerifyChecklist(ctx.cwd)),
1812
- "/verify:整体性验证(分析结果是否属实/成立、引文是否合理、方法是否合理)。",
1813
- "人审不经斜杠命令:Panel「核实」或唤醒选项。",
2307
+ "/check full <焦点>:整体验证(分析结果是否属实/成立、引文是否合理、方法是否合理)。",
2308
+ "人审不经斜杠命令:Panel「核实」或选择框。",
1814
2309
  ].join("\n"), "info");
1815
2310
  return;
1816
2311
  }
1817
2312
  pi.sendUserMessage([
1818
- "/verify — 整体性实质验证(AI)。",
2313
+ "/check full — 整体性实质验证(AI)。",
1819
2314
  `焦点:${focus}`,
1820
2315
  "范围重点:",
1821
2316
  "1) 分析结果是否属实、是否成立:效应方向/量级、不确定性、与脚本输出是否支持正文主张;",
@@ -1823,21 +2318,30 @@ export default function psyclawExtension(pi) {
1823
2318
  "3) 方法是否合理:设计、估计目标、检验/模型选择与研究问题是否匹配;",
1824
2319
  "4) 解释边界:相关≠因果、探索/确证区分、过度声称。",
1825
2320
  "给出可核对的判断(成立 / 存疑 / 不成立)及依据;不得自称已过人审。",
1826
- "人审由交接/定稿门禁自动要求,经 Panel「核实」或唤醒选项完成。",
2321
+ "人审由交接/定稿门禁自动要求,经 Panel「核实」或选择框完成。",
1827
2322
  ].join("\n"), ctx.isIdle() ? {} : { deliverAs: "followUp" });
1828
- ctx.ui.notify(`已启动整体性 /verify(焦点:${focus})。人审由收尾门禁自动要求。`, "info");
2323
+ ctx.ui.notify(`已启动整体验证 /check full(焦点:${focus})。人审由收尾门禁自动要求。`, "info");
1829
2324
  }
1830
2325
  catch (error) {
1831
2326
  await notifyError(ctx, error);
1832
2327
  }
1833
2328
  };
1834
- pi.registerCommand("crosscheck", {
1835
- description: "过程性 AI 核对:数据/引文真实性/格式要求;可附带焦点",
1836
- handler: async (args, ctx) => handleCrosscheck(args, ctx),
1837
- });
1838
- pi.registerCommand("verify", {
1839
- description: "整体性 AI 验证:结果是否成立、引文与方法是否合理;可附带焦点",
1840
- handler: async (args, ctx) => handleVerify(args, ctx),
2329
+ pi.registerCommand("check", {
2330
+ description: "AI 核对:/check quick <焦点> 查数据、引文、格式;/check full <焦点> 查结果、引文、方法是否成立",
2331
+ handler: async (args, ctx) => {
2332
+ const trimmed = args.trim();
2333
+ const [sub = "", ...rest] = trimmed.split(/\s+/);
2334
+ const focus = rest.join(" ");
2335
+ if (sub === "quick")
2336
+ return handleCrosscheck(focus, ctx);
2337
+ if (sub === "full")
2338
+ return handleVerify(focus, ctx);
2339
+ if (trimmed) {
2340
+ ctx.ui.notify("用法:/check quick <焦点>(过程核对)或 /check full <焦点>(整体验证);只输入 /check 查看核对清单。", "error");
2341
+ return;
2342
+ }
2343
+ return handleCrosscheck("", ctx);
2344
+ },
1841
2345
  });
1842
2346
  pi.registerCommand("help", {
1843
2347
  description: "打开 Panel 使用速览",
@@ -1858,27 +2362,37 @@ export default function psyclawExtension(pi) {
1858
2362
  },
1859
2363
  });
1860
2364
  pi.registerCommand("plan", {
1861
- description: "分析方案:单独查看状态,或附带目标文本新建方案",
2365
+ description: "分析方案:/plan 查看状态,/plan <目标> 新建,/plan auto 不经人审批,/plan human 恢复人审",
1862
2366
  handler: async (args, ctx) => {
1863
2367
  try {
1864
2368
  const goal = args.trim();
2369
+ if (goal === "auto" || goal === "human") {
2370
+ const active = await readActiveAnalysisPlan(ctx.cwd);
2371
+ if (!active) {
2372
+ ctx.ui.notify("没有活跃分析方案。先在研究模式里说要分析什么,或 /plan <目标>。", "info");
2373
+ return;
2374
+ }
2375
+ const next = await writeAnalysisPlan(ctx.cwd, advanceAnalysisPlan(active, { type: "set-approval-mode", mode: goal }));
2376
+ ctx.ui.notify(goal === "auto"
2377
+ ? `${formatAnalysisPlanStatus(next)}\n已改为不经人审批:正式分析不再等你批准,所有结果都会标注「未经人审批」。/plan human 恢复。`
2378
+ : `${formatAnalysisPlanStatus(next)}\n已恢复人审:正式分析要等你批准方案。`, "info");
2379
+ return;
2380
+ }
1865
2381
  if (goal) {
1866
2382
  const plan = await writeAnalysisPlan(ctx.cwd, createAnalysisPlan({ goal }));
1867
2383
  ctx.ui.notify(`${formatAnalysisPlanStatus(plan)}\n已按目标创建。用自然语言确认方法(如「可以」);完成后用 /handoff 交接。`, "info");
1868
- pi.sendUserMessage([
1869
- "/skill:analysis-plan",
1870
- "",
2384
+ pi.sendUserMessage(invokeSkill("analysis-plan", [
1871
2385
  `Active plan ${plan.id} created for goal: ${goal}`,
1872
2386
  "Clarify methods with the researcher; prefer natural-language confirmation. Do not invent numbers.",
1873
- ].join("\n"), ctx.isIdle() ? {} : { deliverAs: "followUp" });
2387
+ ].join("\n"), skillLoaded(branchOf(ctx), "analysis-plan")), { expandPromptTemplates: true, ...(ctx.isIdle() ? {} : { deliverAs: "followUp" }) });
1874
2388
  return;
1875
2389
  }
1876
2390
  const plan = await readActiveAnalysisPlan(ctx.cwd);
1877
2391
  if (!plan) {
1878
- ctx.ui.notify("没有活跃分析 Plan。用 /plan <目标> 创建,或在 analysis 模式用自然语言触发 soft takeover。", "info");
2392
+ ctx.ui.notify("没有活跃分析 Plan。用 /plan <目标> 创建,或在研究模式里直接说要分析什么。", "info");
1879
2393
  return;
1880
2394
  }
1881
- ctx.ui.notify(`${formatAnalysisPlanStatus(plan)}\n确认与执行请用自然语言;交接用 /handoff。`, "info");
2395
+ ctx.ui.notify(`${formatAnalysisPlanStatus(plan, (await openDecisions(ctx.cwd, plan.id)).length)}\n${formatDecisionsBrief(await readDecisions(ctx.cwd))}\n确认与执行请用自然语言;交接用 /handoff。`, "info");
1882
2396
  }
1883
2397
  catch (error) {
1884
2398
  await notifyError(ctx, error);
@@ -1896,7 +2410,7 @@ export default function psyclawExtension(pi) {
1896
2410
  }
1897
2411
  let plan = await readActiveAnalysisPlan(ctx.cwd);
1898
2412
  if (!plan) {
1899
- ctx.ui.notify("没有活跃分析 Plan,无法交接。先 /plan <目标> 或在 analysis 模式推进。", "warning");
2413
+ ctx.ui.notify("没有活跃分析 Plan,无法交接。先 /plan <目标>,或在研究模式里推进分析。", "warning");
1900
2414
  return;
1901
2415
  }
1902
2416
  const path = await syncHandoffFromAnalysisPlan(ctx.cwd, plan);
@@ -1906,193 +2420,189 @@ export default function psyclawExtension(pi) {
1906
2420
  : { type: "complete" });
1907
2421
  plan = await writeAnalysisPlan(ctx.cwd, plan);
1908
2422
  }
1909
- ctx.ui.notify(`${formatAnalysisPlanStatus(plan)}\n已写入 ${path}。可切到 academic 模式。`, "info");
2423
+ ctx.ui.notify(`${formatAnalysisPlanStatus(plan)}\n已写入 ${path}。可以接着写论文。`, "info");
1910
2424
  }
1911
2425
  catch (error) {
1912
2426
  await notifyError(ctx, error);
1913
2427
  }
1914
2428
  },
1915
2429
  });
1916
- if (!legacyTestApi)
1917
- pi.registerCommand("grill", {
1918
- description: "逐题追问并压力测试学术研究方案",
1919
- handler: async (args, ctx) => {
1920
- const subject = args.trim();
1921
- pi.sendUserMessage(academicGrillRequest(subject, "review"), ctx.isIdle() ? {} : { deliverAs: "followUp" });
1922
- ctx.ui.notify("已启动学术追问。完成后会先展示文档更新建议,并询问是否写回。", "info");
1923
- },
1924
- });
1925
- if (!legacyTestApi)
1926
- pi.registerCommand("brainstorm", {
1927
- description: "研究方向头脑风暴:提出并比较可选问题",
1928
- handler: async (args, ctx) => {
1929
- const subject = args.trim();
1930
- pi.sendUserMessage(academicBrainstormRequest(subject), ctx.isIdle() ? {} : { deliverAs: "followUp" });
1931
- ctx.ui.notify("已启动研究方向头脑风暴。", "info");
1932
- },
1933
- });
1934
- if (!legacyTestApi)
1935
- pi.registerCommand("review", {
1936
- description: "并发运行多角色模拟同行评审",
1937
- handler: async (_args, ctx) => {
1938
- if (activeAgentRuns.has(ctx.cwd)) {
1939
- ctx.ui.notify("当前项目已有一个多智能体任务正在运行", "warning");
2430
+ const ars_grillCommand = {
2431
+ description: "逐题追问并压力测试学术研究方案",
2432
+ handler: async (args, ctx) => {
2433
+ const subject = args.trim();
2434
+ pi.sendUserMessage(academicGrillRequest(subject, "review"), ctx.isIdle() ? {} : { deliverAs: "followUp" });
2435
+ ctx.ui.notify("已启动学术追问。完成后会先展示文档更新建议,并询问是否写回。", "info");
2436
+ },
2437
+ };
2438
+ const ars_brainstormCommand = {
2439
+ description: "研究方向头脑风暴:提出并比较可选问题",
2440
+ handler: async (args, ctx) => {
2441
+ const subject = args.trim();
2442
+ pi.sendUserMessage(academicBrainstormRequest(subject), ctx.isIdle() ? {} : { deliverAs: "followUp" });
2443
+ ctx.ui.notify("已启动研究方向头脑风暴。", "info");
2444
+ },
2445
+ };
2446
+ const ars_reviewCommand = {
2447
+ description: "并发运行多角色模拟同行评审",
2448
+ handler: async (_args, ctx) => {
2449
+ if (activeAgentRuns.has(ctx.cwd)) {
2450
+ ctx.ui.notify("当前项目已有一个多智能体任务正在运行", "warning");
2451
+ return;
2452
+ }
2453
+ try {
2454
+ const project = await readProject(ctx.cwd);
2455
+ if (!(await readActiveProject(ctx.cwd))) {
2456
+ ctx.ui.notify("请先使用 /init 初始化研究项目;未建仓时不会自动执行同行评审。", "warning");
1940
2457
  return;
1941
2458
  }
1942
- try {
1943
- const project = await readProject(ctx.cwd);
1944
- if (!(await readActiveProject(ctx.cwd))) {
1945
- ctx.ui.notify("请先使用 /init 初始化研究项目;未建仓时不会自动执行同行评审。", "warning");
1946
- return;
1947
- }
1948
- const reviewSkill = _args.trim();
1949
- activeAgentRuns.add(ctx.cwd);
1950
- ctx.ui.notify(`正在使用${reviewSkill?.trim() ? ` Skill“${reviewSkill.trim()}”辅助的` : "默认"} 4 角色并发模拟评审;不会自动改稿。`, "info");
1951
- const result = await runParallelPeerReview({
1952
- root: ctx.cwd,
1953
- project,
1954
- ...(ctx.model?.provider === undefined ? {} : { provider: ctx.model.provider }),
1955
- ...(ctx.model?.id === undefined ? {} : { model: ctx.model.id }),
1956
- env: providerEnvironment(ctx.model?.provider),
1957
- ...(reviewSkill ? { skillGuidance: reviewSkill } : {}),
1958
- onEvent: async (event) => { await new RunEventLog(ctx.cwd, event.runId).append(event); },
1959
- });
1960
- pi.appendEntry("psyclaw:multi-agent-review", {
1961
- runId: result.runId,
1962
- status: result.status,
1963
- outputPath: result.outputPath,
1964
- adoption: "review-output-only",
1965
- recordedAt: new Date().toISOString(),
1966
- });
1967
- ctx.ui.notify(`模拟审稿${result.status === "completed" ? "已完成" : "未完整完成"}:${result.outputPath}。审稿意见仅供研究者决定是否采纳。`, result.status === "completed" ? "info" : "warning");
1968
- }
1969
- catch (error) {
1970
- await notifyError(ctx, error);
1971
- }
1972
- finally {
1973
- activeAgentRuns.delete(ctx.cwd);
2459
+ const reviewSkill = _args.trim();
2460
+ activeAgentRuns.add(ctx.cwd);
2461
+ ctx.ui.notify(`正在使用${reviewSkill?.trim() ? ` Skill“${reviewSkill.trim()}”辅助的` : "默认"} 4 角色并发模拟评审;不会自动改稿。`, "info");
2462
+ const result = await runParallelPeerReview({
2463
+ root: ctx.cwd,
2464
+ project,
2465
+ ...(ctx.model?.provider === undefined ? {} : { provider: ctx.model.provider }),
2466
+ ...(ctx.model?.id === undefined ? {} : { model: ctx.model.id }),
2467
+ env: providerEnvironment(ctx.model?.provider),
2468
+ ...(reviewSkill ? { skillGuidance: reviewSkill } : {}),
2469
+ onEvent: async (event) => { await new RunEventLog(ctx.cwd, event.runId).append(event); },
2470
+ });
2471
+ pi.appendEntry("psyclaw:multi-agent-review", {
2472
+ runId: result.runId,
2473
+ status: result.status,
2474
+ outputPath: result.outputPath,
2475
+ adoption: "review-output-only",
2476
+ recordedAt: new Date().toISOString(),
2477
+ });
2478
+ ctx.ui.notify(`模拟审稿${result.status === "completed" ? "已完成" : "未完整完成"}:${result.outputPath}。审稿意见仅供研究者决定是否采纳。`, result.status === "completed" ? "info" : "warning");
2479
+ }
2480
+ catch (error) {
2481
+ await notifyError(ctx, error);
2482
+ }
2483
+ finally {
2484
+ activeAgentRuns.delete(ctx.cwd);
2485
+ }
2486
+ },
2487
+ };
2488
+ const ars_loopCommand = {
2489
+ description: "按计划循环推进当前研究阶段",
2490
+ handler: async (args, ctx) => {
2491
+ const requested = args.trim();
2492
+ if (requested.toLowerCase() === "stop") {
2493
+ if (ctx.isIdle())
2494
+ ctx.ui.notify("当前没有正在运行的研究循环", "info");
2495
+ else {
2496
+ ctx.abort();
2497
+ ctx.ui.notify("已请求停止当前研究循环", "warning");
1974
2498
  }
1975
- },
1976
- });
2499
+ return;
2500
+ }
2501
+ let project;
2502
+ try {
2503
+ project = await readProject(ctx.cwd);
2504
+ }
2505
+ catch {
2506
+ ctx.ui.notify("请先使用 /init 初始化研究项目,再运行 /ars loop", "warning");
2507
+ return;
2508
+ }
2509
+ if (!(await readActiveProject(ctx.cwd))) {
2510
+ ctx.ui.notify("请先使用 /init 初始化研究项目,再运行 /ars loop。", "warning");
2511
+ return;
2512
+ }
2513
+ const objective = requested || project.goal;
2514
+ const request = [
2515
+ "运行一个有边界的 PsyClaw 研究循环,采用计划、执行、检查、修正的顺序推进当前研究阶段。",
2516
+ `本轮目标:${objective}`,
2517
+ "开始前读取 .psyclaw/project.json、notes/goal.md 和 notes/plan.md;如果当前对话或项目中存在经研究者确认的 /ars grill 研究规格,以该规格细化初始计划,但不得违反系统规则、AGENTS.md 或研究门禁。",
2518
+ "先识别当前最高优先级且前提已满足的一个任务,再使用可用工具实际推进。不要只描述准备做什么。普通项目文件写入、脚本和可恢复工具调用在已 /init 的项目中连续推进;原始数据覆盖、凭据、外部发布、破坏性操作仍遵守单独的安全边界。",
2519
+ "每完成一个实质步骤就检查产物、证据和计划是否一致。缺失信息若能检索、计算、重跑、改写或明确标注,应先自行修复。只有存在会改变研究问题、样本处理、操作化、估计目标、方法或解释的实质分歧时才请求研究者取舍;权限边界、不可恢复错误或当前阶段完成时停止。不得为了继续循环而虚构输入或结论。",
2520
+ "本次最多推进一个可验收的研究阶段。结束时简要报告已完成、已核验、阻塞、计划变化和下一步;规划内容不得表述为已有研究证据。",
2521
+ ].join("\n");
2522
+ pi.sendUserMessage(request, ctx.isIdle() ? {} : { deliverAs: "followUp" });
2523
+ ctx.ui.notify("已启动有界研究循环;使用 /ars loop stop 可请求中止", "info");
2524
+ },
2525
+ };
1977
2526
  if (!legacyTestApi)
1978
- pi.registerCommand("loop", {
1979
- description: "按计划循环推进当前研究阶段",
2527
+ pi.registerCommand("create", {
2528
+ description: "预览并创建项目级 skill、hook、rule 或 subagent:/create <种类> <名称与需求>",
1980
2529
  handler: async (args, ctx) => {
1981
- const requested = args.trim();
1982
- if (requested.toLowerCase() === "stop") {
1983
- if (ctx.isIdle())
1984
- ctx.ui.notify("当前没有正在运行的研究循环", "info");
1985
- else {
1986
- ctx.abort();
1987
- ctx.ui.notify("已请求停止当前研究循环", "warning");
1988
- }
2530
+ const [kind = "", ...rest] = args.trim().split(/\s+/);
2531
+ const requirements = rest.join(" ").trim();
2532
+ const kinds = ["skill", "hook", "rule", "subagent"];
2533
+ if (!kinds.includes(kind) || !requirements) {
2534
+ ctx.ui.notify("请使用 /create <skill|hook|rule|subagent> <名称与需求描述>", "info");
1989
2535
  return;
1990
2536
  }
1991
- let project;
1992
- try {
1993
- project = await readProject(ctx.cwd);
1994
- }
1995
- catch {
1996
- ctx.ui.notify("请先使用 /init 初始化研究项目,再运行 /loop", "warning");
1997
- return;
1998
- }
1999
- if (!(await readActiveProject(ctx.cwd))) {
2000
- ctx.ui.notify("请先使用 /init 初始化研究项目,再运行 /loop。", "warning");
2001
- return;
2002
- }
2003
- const objective = requested || project.goal;
2004
- const request = [
2005
- "运行一个有边界的 PsyClaw 研究循环,采用计划、执行、检查、修正的顺序推进当前研究阶段。",
2006
- `本轮目标:${objective}`,
2007
- "开始前读取 .psyclaw/project.json、notes/goal.md 和 notes/plan.md;如果当前对话或项目中存在经研究者确认的 /grill 研究规格,以该规格细化初始计划,但不得违反系统规则、AGENTS.md 或研究门禁。",
2008
- "先识别当前最高优先级且前提已满足的一个任务,再使用可用工具实际推进。不要只描述准备做什么。普通项目文件写入、脚本和可恢复工具调用在已 /init 的项目中连续推进;原始数据覆盖、凭据、外部发布、破坏性操作仍遵守单独的安全边界。",
2009
- "每完成一个实质步骤就检查产物、证据和计划是否一致。缺失信息若能检索、计算、重跑、改写或明确标注,应先自行修复。只有存在会改变研究问题、样本处理、操作化、估计目标、方法或解释的实质分歧时才请求研究者取舍;权限边界、不可恢复错误或当前阶段完成时停止。不得为了继续循环而虚构输入或结论。",
2010
- "本次最多推进一个可验收的研究阶段。结束时简要报告已完成、已核验、阻塞、计划变化和下一步;规划内容不得表述为已有研究证据。",
2011
- ].join("\n");
2012
- pi.sendUserMessage(request, ctx.isIdle() ? {} : { deliverAs: "followUp" });
2013
- ctx.ui.notify("已启动有界研究循环;使用 /loop stop 可请求中止", "info");
2537
+ pi.sendUserMessage(creationCommandPrompt(kind, requirements), ctx.isIdle() ? {} : { deliverAs: "followUp" });
2014
2538
  },
2015
2539
  });
2016
- for (const kind of ["skill", "hook", "rule", "subagent"]) {
2017
- if (!legacyTestApi)
2018
- pi.registerCommand(`create-${kind}`, {
2019
- description: `预览并创建项目级 ${kind}(附带名称与需求文本)`,
2020
- handler: async (args, ctx) => {
2021
- const requirements = args.trim();
2022
- if (!requirements) {
2023
- ctx.ui.notify(`请使用 /create-${kind} <名称与需求描述>`, "info");
2024
- return;
2025
- }
2026
- pi.sendUserMessage(creationCommandPrompt(kind, requirements), ctx.isIdle() ? {} : { deliverAs: "followUp" });
2027
- },
2028
- });
2029
- }
2030
2540
  if (!legacyTestApi)
2031
2541
  pi.registerCommand("skill", {
2032
- description: "打开 Skill 管理页",
2033
- handler: async (_args, ctx) => {
2034
- try {
2035
- await showSkillManager(pi, ctx);
2036
- }
2037
- catch (error) {
2038
- await notifyError(ctx, error);
2039
- }
2040
- },
2041
- });
2042
- if (!legacyTestApi)
2043
- pi.registerCommand("skill-preference", {
2044
- description: "查看或重置方法主题与用户 skill 的冲突选择",
2542
+ description: "打开 Skill 管理页;/skill preference [reset] 查看或重置方法主题的 skill 选择",
2045
2543
  handler: async (args, ctx) => {
2544
+ const [sub = "", ...rest] = args.trim().split(/\s+/);
2545
+ if (sub === "preference")
2546
+ return skillPreferenceHandler(rest.join(" "), ctx);
2046
2547
  try {
2047
- if (args.trim() === "reset") {
2048
- await writeSkillPreferences(ctx.cwd, { schemaVersion: "psyclaw/skill-preferences/v1", choices: {} });
2049
- ctx.ui.notify("已重置方法主题的 skill 选择。下次冲突会再问。", "info");
2050
- return;
2051
- }
2052
- const preferences = await readSkillPreferences(ctx.cwd);
2053
- const lines = Object.entries(preferences.choices);
2054
- ctx.ui.notify(lines.length === 0 ? "没有已保存的方法 skill 选择。" : lines.map(([key, value]) => `${key}: ${value}`).join("\n"), "info");
2055
- }
2056
- catch (error) {
2057
- await notifyError(ctx, error);
2058
- }
2059
- },
2060
- });
2061
- if (!legacyTestApi)
2062
- pi.registerCommand("biosignal", {
2063
- description: "生理信号分析能力包:选型研究域并安装 MCP/Skill",
2064
- handler: async (_args, ctx) => {
2065
- try {
2066
- await showBiosignalPack(pi, ctx, runtimeMcps);
2548
+ await showSkillManager(pi, ctx);
2067
2549
  }
2068
2550
  catch (error) {
2069
2551
  await notifyError(ctx, error);
2070
2552
  }
2071
2553
  },
2072
2554
  });
2555
+ const skillPreferenceHandler = async (args, ctx) => {
2556
+ try {
2557
+ if (args.trim() === "reset") {
2558
+ await writeSkillPreferences(ctx.cwd, { schemaVersion: "psyclaw/skill-preferences/v1", choices: {} });
2559
+ ctx.ui.notify("已重置方法主题的 skill 选择。下次冲突会再问。", "info");
2560
+ return;
2561
+ }
2562
+ const preferences = await readSkillPreferences(ctx.cwd);
2563
+ const lines = Object.entries(preferences.choices);
2564
+ ctx.ui.notify(lines.length === 0 ? "没有已保存的方法 skill 选择。" : lines.map(([key, value]) => `${key}: ${value}`).join("\n"), "info");
2565
+ }
2566
+ catch (error) {
2567
+ await notifyError(ctx, error);
2568
+ }
2569
+ };
2073
2570
  if (!legacyTestApi)
2074
2571
  pi.registerCommand("ars", {
2075
- description: "学术模式:单独开启,或附带任务文本启动完整流程",
2572
+ description: "学术流程:/ars 开启,/ars stop 关闭,/ars <任务> 走完整流程;子命令 grill、brainstorm、review、loop",
2076
2573
  handler: async (args, ctx) => {
2077
2574
  try {
2078
2575
  const trailing = args.trim();
2576
+ const [first = "", ...restWords] = trailing.split(/\s+/);
2577
+ const subcommands = {
2578
+ grill: ars_grillCommand,
2579
+ brainstorm: ars_brainstormCommand,
2580
+ review: ars_reviewCommand,
2581
+ loop: ars_loopCommand,
2582
+ };
2583
+ const sub = subcommands[first.toLowerCase()];
2584
+ if (sub) {
2585
+ await sub.handler(restWords.join(" "), ctx);
2586
+ return;
2587
+ }
2079
2588
  if (!trailing) {
2080
2589
  if (!ctx.hasUI) {
2081
- ctx.ui.notify("当前环境无编辑器;请改用 Shift+Tab 切换 academic。", "info");
2590
+ ctx.ui.notify("当前环境无编辑器;请直接用 /ars <任务> 启动学术流程。", "info");
2082
2591
  return;
2083
2592
  }
2084
2593
  arsUiContext = ctx;
2085
- applySessionMode("academic");
2594
+ setArsPiSessionActive(pi.appendEntry.bind(pi), true);
2595
+ ctx.ui.notify("已开启学术流程(ARS);/ars stop 关闭。", "info");
2086
2596
  return;
2087
2597
  }
2088
2598
  const lower = trailing.toLowerCase();
2089
2599
  if (lower === "stop") {
2090
2600
  arsUiContext = ctx;
2091
- applySessionMode("chat");
2601
+ setArsPiSessionActive(pi.appendEntry.bind(pi), false);
2092
2602
  if (ctx.hasUI && isArsModeEditorText(ctx.ui.getEditorText?.() ?? "")) {
2093
2603
  ctx.ui.setEditorText("");
2094
2604
  }
2095
- ctx.ui.notify("已回到 chat 模式", "info");
2605
+ ctx.ui.notify("已关闭学术流程(ARS)", "info");
2096
2606
  return;
2097
2607
  }
2098
2608
  if (lower === "doctor") {
@@ -2146,8 +2656,17 @@ export default function psyclawExtension(pi) {
2146
2656
  });
2147
2657
  if (!legacyTestApi)
2148
2658
  pi.registerCommand("mcp", {
2149
- description: "打开 MCP 安装与配置管理页",
2150
- handler: async (_args, ctx) => {
2659
+ description: "打开 MCP 安装与配置管理页;/mcp biosignal 打开生理信号分析能力包",
2660
+ handler: async (args, ctx) => {
2661
+ if (args.trim() === "biosignal") {
2662
+ try {
2663
+ await showBiosignalPack(pi, ctx, runtimeMcps);
2664
+ }
2665
+ catch (error) {
2666
+ await notifyError(ctx, error);
2667
+ }
2668
+ return;
2669
+ }
2151
2670
  try {
2152
2671
  await showMcpManager(pi, ctx, runtimeMcps);
2153
2672
  }
@@ -2285,186 +2804,69 @@ export default function psyclawExtension(pi) {
2285
2804
  }
2286
2805
  },
2287
2806
  });
2807
+ const petCommand = {
2808
+ description: "启动横幅宠物:单独查看状态,或附带 on/off",
2809
+ handler: async (args, ctx) => {
2810
+ const action = args.trim().toLowerCase() || "status";
2811
+ if (action === "status") {
2812
+ ctx.ui.notify(`启动横幅宠物:${await petPreference() ? "已开启" : "已关闭(默认)"}`, "info");
2813
+ return;
2814
+ }
2815
+ if (action !== "on" && action !== "off") {
2816
+ ctx.ui.notify("请使用 /prefs pet,或 /prefs pet on|off", "error");
2817
+ return;
2818
+ }
2819
+ await setPetPreference(action === "on");
2820
+ ctx.ui.notify(`启动横幅宠物已${action === "on" ? "开启" : "关闭"},下次启动生效`, "info");
2821
+ },
2822
+ };
2823
+ const telemetryCommand = {
2824
+ description: "查看或关闭匿名产品遥测",
2825
+ handler: async (args, ctx) => {
2826
+ const action = args.trim().toLowerCase() || "status";
2827
+ if (action === "status") {
2828
+ const preference = await readTelemetryPreference();
2829
+ ctx.ui.notify(preference.enabled
2830
+ ? "匿名产品遥测:开启(默认)。采集粗粒度使用与错误,不含研究正文。关闭:/prefs telemetry off"
2831
+ : "匿名产品遥测:已关闭。重新开启:/prefs telemetry on", "info");
2832
+ return;
2833
+ }
2834
+ if (action !== "on" && action !== "off") {
2835
+ ctx.ui.notify("用法:/prefs telemetry on|off", "error");
2836
+ return;
2837
+ }
2838
+ await writeTelemetryPreference({ enabled: action === "on", noticeAcknowledged: true });
2839
+ ctx.ui.notify(action === "on" ? "已开启匿名产品遥测。下次启动生效。" : "已关闭匿名产品遥测。下次启动不再发送。", "info");
2840
+ },
2841
+ };
2288
2842
  if (!legacyTestApi)
2289
- pi.registerCommand("pet", {
2290
- description: "启动横幅宠物:单独查看状态,或附带 on/off",
2291
- handler: async (args, ctx) => {
2292
- const action = args.trim().toLowerCase() || "status";
2293
- if (action === "status") {
2294
- ctx.ui.notify(`启动横幅宠物:${await petPreference() ? "已开启" : "已关闭(默认)"}`, "info");
2295
- return;
2296
- }
2297
- if (action !== "on" && action !== "off") {
2298
- ctx.ui.notify("请使用 /pet,或 /pet on|off", "error");
2299
- return;
2300
- }
2301
- await setPetPreference(action === "on");
2302
- ctx.ui.notify(`启动横幅宠物已${action === "on" ? "开启" : "关闭"},下次启动生效`, "info");
2303
- },
2304
- });
2305
- if (!legacyTestApi)
2306
- pi.registerCommand("telemetry", {
2307
- description: "查看或关闭匿名产品遥测",
2843
+ pi.registerCommand("prefs", {
2844
+ description: "偏好设置:/prefs pet [on|off] 启动横幅宠物,/prefs telemetry [on|off] 匿名产品遥测",
2308
2845
  handler: async (args, ctx) => {
2309
- const action = args.trim().toLowerCase() || "status";
2310
- if (action === "status") {
2311
- const preference = await readTelemetryPreference();
2312
- ctx.ui.notify(preference.enabled
2313
- ? "匿名产品遥测:开启(默认)。采集粗粒度使用与错误,不含研究正文。关闭:/telemetry off"
2314
- : "匿名产品遥测:已关闭。重新开启:/telemetry on", "info");
2315
- return;
2316
- }
2317
- if (action !== "on" && action !== "off") {
2318
- ctx.ui.notify("Usage: /telemetry on|off|status", "error");
2846
+ const [sub = "", ...rest] = args.trim().split(/\s+/);
2847
+ if (sub === "pet")
2848
+ return petCommand.handler(rest.join(" "), ctx);
2849
+ if (sub === "telemetry")
2850
+ return telemetryCommand.handler(rest.join(" "), ctx);
2851
+ if (sub) {
2852
+ ctx.ui.notify("用法:/prefs pet [on|off] 或 /prefs telemetry [on|off]", "error");
2319
2853
  return;
2320
2854
  }
2321
- await writeTelemetryPreference({ enabled: action === "on", noticeAcknowledged: true });
2322
- ctx.ui.notify(action === "on" ? "已开启匿名产品遥测。下次启动生效。" : "已关闭匿名产品遥测。下次启动不再发送。", "info");
2855
+ await petCommand.handler("", ctx);
2856
+ await telemetryCommand.handler("", ctx);
2323
2857
  },
2324
2858
  });
2325
2859
  if (typeof pi.registerTool === "function") {
2326
2860
  registerAnalysisRuntimeTools(pi);
2327
- pi.registerTool({
2328
- name: "psyclaw_research_decision",
2329
- label: "Research decision",
2330
- description: "Request researcher input only for an unresolved substantive research trade-off. Never use this for software, formatting, missing reporting fields, recoverable errors, evidence collection, credentials, publication, or other operational authorization.",
2331
- parameters: Type.Object({
2332
- id: Type.String({ minLength: 1 }),
2333
- question: Type.String({ minLength: 1 }),
2334
- options: Type.Array(Type.Object({
2335
- id: Type.String({ minLength: 1 }),
2336
- label: Type.String({ minLength: 1 }),
2337
- rationale: Type.String({ minLength: 1 }),
2338
- consequences: Type.Array(Type.String()),
2339
- evidenceRefs: Type.Array(Type.String()),
2340
- }), { minItems: 2 }),
2341
- affectedAreas: Type.Array(Type.Union([
2342
- Type.Literal("research-question"),
2343
- Type.Literal("sample-treatment"),
2344
- Type.Literal("operationalization"),
2345
- Type.Literal("estimand"),
2346
- Type.Literal("analysis-method"),
2347
- Type.Literal("interpretation"),
2348
- ]), { minItems: 1 }),
2349
- evidenceCannotResolve: Type.Boolean(),
2350
- evidenceReviewed: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
2351
- methodsChecked: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
2352
- unresolvedReason: Type.String({ minLength: 1 }),
2353
- recommendation: Type.String({ minLength: 1 }),
2354
- }),
2355
- executionMode: "sequential",
2356
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
2357
- const run = await readActiveProject(ctx.cwd);
2358
- if (!run) {
2359
- return {
2360
- content: [{ type: "text", text: "当前目录尚未 /init,不能进入研究决策状态。请先执行 /init。" }],
2361
- details: { status: "general-mode" },
2362
- isError: true,
2363
- };
2364
- }
2365
- const request = {
2366
- schemaVersion: "psyclaw/research-decision/v1",
2367
- id: params.id,
2368
- question: params.question,
2369
- options: params.options,
2370
- affectedAreas: params.affectedAreas,
2371
- evidenceCannotResolve: params.evidenceCannotResolve,
2372
- evidenceReviewed: params.evidenceReviewed,
2373
- methodsChecked: params.methodsChecked,
2374
- unresolvedReason: params.unresolvedReason,
2375
- recommendation: params.recommendation,
2376
- };
2377
- try {
2378
- assertResearchDecision(request);
2379
- }
2380
- catch (error) {
2381
- return {
2382
- content: [{ type: "text", text: `该事项不符合研究取舍条件:${error instanceof Error ? error.message : String(error)}。请继续检索、计算、修复,或按单独的安全授权边界处理。` }],
2383
- details: { status: "not-a-research-decision", runId: run.runId },
2384
- isError: true,
2385
- };
2386
- }
2387
- const eventLog = new RunEventLog(ctx.cwd, run.runId);
2388
- const events = await eventLog.snapshot();
2389
- const resolvedIds = new Set(events
2390
- .filter((event) => event.type === "decision-resolved" && event.researchDecisionResolution)
2391
- .map((event) => event.researchDecisionResolution.decisionId));
2392
- const pending = findLastMatching(events, (event) => event.type === "awaiting-human" && Boolean(event.researchDecision && !resolvedIds.has(event.researchDecision.id)));
2393
- if (pending?.researchDecision) {
2394
- return {
2395
- content: [{ type: "text", text: `当前已有一项待研究者取舍的问题:${pending.researchDecision.question}。请先处理该问题,不能同时创建第二项。` }],
2396
- details: { status: "research-decision-already-pending", runId: run.runId, decisionId: pending.researchDecision.id },
2397
- isError: true,
2398
- };
2399
- }
2400
- if (events.some((event) => event.researchDecision?.id === request.id || event.researchDecisionResolution?.decisionId === request.id)) {
2401
- return {
2402
- content: [{ type: "text", text: `研究取舍编号已使用:${request.id}` }],
2403
- details: { status: "duplicate-research-decision", runId: run.runId, decisionId: request.id },
2404
- isError: true,
2405
- };
2406
- }
2407
- await eventLog.append({
2408
- type: "awaiting-human",
2409
- at: new Date().toISOString(),
2410
- researchDecision: request,
2411
- message: request.question,
2412
- });
2413
- return {
2414
- content: [{ type: "text", text: JSON.stringify({ status: "需要研究者取舍", runId: run.runId, decision: request }, null, 2) }],
2415
- details: { status: "awaiting-human", runId: run.runId, decisionId: request.id },
2416
- };
2417
- },
2418
- });
2419
- pi.registerTool({
2420
- name: "psyclaw_resolve_research_decision",
2421
- label: "Resolve research decision",
2422
- description: "Record the researcher's answer to the current substantive research trade-off and resume the controlled workflow. This is not an operational approval tool.",
2423
- parameters: Type.Object({
2424
- decisionId: Type.String({ minLength: 1 }),
2425
- selectedOption: Type.String({ minLength: 1 }),
2426
- rationale: Type.String({ minLength: 1 }),
2427
- }),
2428
- executionMode: "sequential",
2429
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
2430
- const run = await readActiveProject(ctx.cwd);
2431
- if (!run) {
2432
- return { content: [{ type: "text", text: "当前目录尚未 /init,没有有效的研究项目。" }], details: { status: "general-mode" }, isError: true };
2433
- }
2434
- const eventLog = new RunEventLog(ctx.cwd, run.runId);
2435
- const events = await eventLog.snapshot();
2436
- const resolvedIds = new Set(events
2437
- .filter((event) => event.type === "decision-resolved" && event.researchDecisionResolution)
2438
- .map((event) => event.researchDecisionResolution.decisionId));
2439
- const pending = findLastMatching(events, (event) => event.type === "awaiting-human" && event.researchDecision?.id === params.decisionId && !resolvedIds.has(params.decisionId));
2440
- if (!pending?.researchDecision) {
2441
- return { content: [{ type: "text", text: `未找到待处理的研究取舍:${params.decisionId}` }], details: { status: "not-found", runId: run.runId }, isError: true };
2442
- }
2443
- try {
2444
- const resolution = resolveResearchDecision(pending.researchDecision, {
2445
- selectedOption: params.selectedOption,
2446
- rationale: params.rationale,
2447
- });
2448
- await eventLog.append({ type: "decision-resolved", at: resolution.resolvedAt, researchDecisionResolution: resolution });
2449
- return {
2450
- content: [{ type: "text", text: JSON.stringify({ status: "executing", runId: run.runId, resolution }, null, 2) }],
2451
- details: { status: "executing", runId: run.runId, decisionId: resolution.decisionId },
2452
- };
2453
- }
2454
- catch (error) {
2455
- return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], details: { status: "invalid-resolution", runId: run.runId }, isError: true };
2456
- }
2457
- },
2458
- });
2459
2861
  pi.registerTool({
2460
2862
  name: "psyclaw_mcp",
2461
2863
  label: "MCP tools",
2462
- description: "List and call tools from MCP servers enabled in .psyclaw/mcp/*.json. Use action=list first, then action=call with the exact server and tool names.",
2864
+ description: "List and call tools from MCP servers enabled in .psyclaw/mcp/*.json. action=list gives one line per tool (name, what it does, parameters; * = required); action=list with server and tool gives that tool's full input schema. Then action=call with the exact server and tool names.",
2463
2865
  promptSnippet: "Discover and call enabled MCP servers such as MNE through PsyClaw.",
2464
2866
  parameters: Type.Object({
2465
2867
  action: Type.Union([Type.Literal("list"), Type.Literal("call")]),
2466
2868
  server: Type.Optional(Type.String({ description: "Configured MCP server id, for example mne-mcp" })),
2467
- tool: Type.Optional(Type.String({ description: "Exact MCP tool name returned by action=list" })),
2869
+ tool: Type.Optional(Type.String({ description: "Exact MCP tool name returned by action=list (with action=list: show its full schema)" })),
2468
2870
  input: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
2469
2871
  }),
2470
2872
  executionMode: "sequential",
@@ -2472,7 +2874,7 @@ export default function psyclawExtension(pi) {
2472
2874
  try {
2473
2875
  if (params.action === "list") {
2474
2876
  const servers = await runtimeMcps.list(ctx.cwd, params.server);
2475
- return { content: [{ type: "text", text: JSON.stringify({ servers }, null, 2) }], details: { action: "list", servers: servers.length } };
2877
+ return { content: [{ type: "text", text: formatMcpListing(servers, params.tool) }], details: { action: "list", servers: servers.length } };
2476
2878
  }
2477
2879
  if (!(await readActiveProject(ctx.cwd))) {
2478
2880
  return {
@@ -2484,7 +2886,12 @@ export default function psyclawExtension(pi) {
2484
2886
  if (!params.server || !params.tool)
2485
2887
  throw new Error("server and tool are required for action=call");
2486
2888
  const result = await runtimeMcps.call(ctx.cwd, params.server, params.tool, params.input ?? {});
2487
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }], details: { action: "call", server: params.server, tool: params.tool } };
2889
+ const unwrapped = unwrapMcpResult(result);
2890
+ return {
2891
+ content: [{ type: "text", text: unwrapped.text }],
2892
+ details: { action: "call", server: params.server, tool: params.tool },
2893
+ ...(unwrapped.isError ? { isError: true } : {}),
2894
+ };
2488
2895
  }
2489
2896
  catch (error) {
2490
2897
  return {
@@ -2604,25 +3011,44 @@ export default function psyclawExtension(pi) {
2604
3011
  });
2605
3012
  pi.registerTool({
2606
3013
  name: "psyclaw_skill",
2607
- label: "Research skill",
2608
- description: "Load one trusted bundled psyclaw core skill and make its use visible to the user. Use this instead of directly reading a core SKILL.md file.",
3014
+ label: "Skill",
3015
+ description: "Find or load a skill. action=find with a few words about the task lists the skills that fit, with what each does. name=<skill> loads that skill's instructions (any skill listed in available_skills). Load a skill only when the task needs it; do not read skill files directly.",
2609
3016
  parameters: Type.Object({
2610
- name: Type.String({ description: "Core skill name: academic-grill, research-intake, evidence-capture, citation-audit, or analysis-plan" }),
3017
+ action: Type.Optional(Type.Union([Type.Literal("load"), Type.Literal("find")])),
3018
+ name: Type.Optional(Type.String({ description: "Skill name from available_skills (action=load)" })),
3019
+ query: Type.Optional(Type.String({ description: "A few words about the task (action=find)" })),
3020
+ section: Type.Optional(Type.String({ description: "Load only this section of the skill (its heading), e.g. one listed under 'Sections loaded on demand'" })),
2611
3021
  purpose: Type.Optional(Type.String({ description: "Short user-facing reason for using this skill now" })),
2612
3022
  }),
2613
3023
  executionMode: "sequential",
2614
3024
  async execute(_toolCallId, params) {
2615
- const name = params.name.trim();
2616
- if (!CORE_SKILLS.has(name)) {
3025
+ if (params.action === "find" || (!params.name && params.query)) {
3026
+ const hits = findSkills(skillRegistry, params.query ?? params.name ?? "");
3027
+ const text = hits.length
3028
+ ? hits.map((skill) => `- ${skill.name} (${skill.group}): ${firstSentence(skill.description, 220)}`).join("\n")
3029
+ : "No listed skill matches those words. Try other words, or work without a skill.";
3030
+ return { content: [{ type: "text", text }], details: { status: "found", name: hits.map((skill) => skill.name).join(",") } };
3031
+ }
3032
+ const name = (params.name ?? "").trim();
3033
+ const listed = skillRegistry.find((skill) => skill.name === name);
3034
+ const path = CORE_SKILLS.has(name) ? coreSkillPath(name) : listed?.location;
3035
+ if (!path) {
2617
3036
  return {
2618
- content: [{ type: "text", text: `Skill not available in the trusted core pack: ${name}` }],
3037
+ content: [{ type: "text", text: `No skill named ${name || "(none)"}. Use action=find to look one up.` }],
2619
3038
  details: { status: "blocked", name },
2620
3039
  };
2621
3040
  }
2622
3041
  try {
2623
- const instructions = await readFile(coreSkillPath(name), "utf8");
3042
+ if (params.section) {
3043
+ const text = readSkillSection(path, params.section);
3044
+ return {
3045
+ content: [{ type: "text", text: text ?? `No section starting with "${params.section}" in ${name}.` }],
3046
+ details: { status: text ? "active" : "failed", name },
3047
+ };
3048
+ }
3049
+ const instructions = await readFile(path, "utf8");
2624
3050
  return {
2625
- content: [{ type: "text", text: `正在使用 Skill:${name}${params.purpose ? `(${params.purpose})` : ""}\n\n${instructions}` }],
3051
+ content: [{ type: "text", text: `正在使用 Skill:${name}${params.purpose ? `(${params.purpose})` : ""}\nSkill directory (resolve relative paths against it): ${dirname(path)}\n\n${instructions}` }],
2626
3052
  details: { status: "active", name, ...(params.purpose === undefined ? {} : { purpose: params.purpose }) },
2627
3053
  };
2628
3054
  }
@@ -2652,7 +3078,7 @@ export default function psyclawExtension(pi) {
2652
3078
  const project = await readActiveProject(ctx.cwd);
2653
3079
  const softNote = project
2654
3080
  ? undefined
2655
- : "尚未 /init(软门禁):继续执行;收尾前须 AI /crosscheck 后人审。建议先 /init 建仓。";
3081
+ : "尚未 /init(软门禁):继续执行;收尾前须 AI /check quick 后人审。建议先 /init 建仓。";
2656
3082
  const request = params.request.trim();
2657
3083
  const combined = `${request} ${params.identifier ?? ""}`;
2658
3084
  const explicitWorkflow = params.workflow?.trim();
@@ -2771,40 +3197,541 @@ export default function psyclawExtension(pi) {
2771
3197
  },
2772
3198
  });
2773
3199
  pi.registerTool({
2774
- name: "psyclaw_record_choice",
2775
- label: "记录选择",
2776
- description: "记录研究者对选项的回应。结构化唤醒选项或直接文本回应都必须记录;直接回应需保留原文并填写解析后的选项。",
3200
+ name: "psyclaw_spec",
3201
+ label: "估计量说明书",
3202
+ description: "The analysis specification (analysis mode): analysis/spec.json, one estimand per quantity the study reports. action=write: estimands {E1: {rq, quantity, shell, attrs: {population, outcome, contrast, summary, model, adjustment, missing, interval}}}, each attribute {value, by: brief|researcher, quote} or {by: analyst|open, options: [...], recommended: <number>, reason}; estimands not given are kept, null removes one without a result. action=confirm (no id): code returns one numbered message with every open choice of every estimand still to confirm; post it as your whole reply and stop. action=answers: the researcher's one reply (quote, answers [{item: E1.2, option or text}], rest, additions). action=confirm id=E1: choice boxes for an estimand the reply left unclear. action=record id, values, evidence_file: the numbers of a confirmed estimand and the output file that holds them. action=waive id, reason. action=status: what is still missing.",
2777
3203
  parameters: Type.Object({
2778
- prompt: Type.String({ minLength: 1, description: "当时向研究者提出的问题或选择提示" }),
2779
- originalResponse: Type.String({ minLength: 1, description: "研究者的原始回应,不能改写或省略" }),
2780
- selectedIds: Type.Array(Type.String(), { description: "解析后的选项 ID;无法明确解析时为空" }),
2781
- selectedLabels: Type.Array(Type.String(), { description: "解析后的选项名称" }),
2782
- source: Type.Union([Type.Literal("tool"), Type.Literal("free-text")]),
2783
- context: Type.Optional(Type.String({ description: "选择发生时的研究或任务上下文" })),
3204
+ action: Type.Union([Type.Literal("write"), Type.Literal("confirm"), Type.Literal("answers"), Type.Literal("record"), Type.Literal("waive"), Type.Literal("status")]),
3205
+ answers: Type.Optional(Type.Array(Type.Object({ item: Type.String({ description: "E1.2" }), option: Type.Optional(Type.Number({ description: "1-based option number" })), text: Type.Optional(Type.String({ description: "The researcher's own approach, in their words" })) }))),
3206
+ rest: Type.Optional(Type.Union([Type.Literal("recommended"), Type.Literal("open")])),
3207
+ quote: Type.Optional(Type.String({ description: "answers: the researcher's reply, unchanged" })),
3208
+ additions: Type.Optional(Type.Array(Type.String())),
3209
+ estimands: Type.Optional(Type.Object({}, { additionalProperties: true })),
3210
+ id: Type.Optional(Type.String()),
3211
+ values: Type.Optional(Type.Object({}, { additionalProperties: true })),
3212
+ evidence_file: Type.Optional(Type.String()),
3213
+ reason: Type.Optional(Type.String()),
2784
3214
  }),
2785
3215
  executionMode: "sequential",
2786
3216
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
3217
+ const out = (text, isError = false) => ({ content: [{ type: "text", text }], details: undefined, ...(isError ? { isError: true } : {}) });
2787
3218
  try {
2788
- const record = await appendChoiceRecord(ctx.cwd, {
2789
- prompt: params.prompt,
2790
- originalResponse: params.originalResponse,
2791
- selectedIds: params.selectedIds,
2792
- selectedLabels: params.selectedLabels,
2793
- source: params.source,
3219
+ const cwd = ctx.cwd;
3220
+ if (params.action === "write") {
3221
+ return out(writeSpec(cwd, params.estimands, estimandRqs(cwd, ctx), `${materialsText(cwd)}\n${userTexts(ctx)}`, userTexts(ctx)));
3222
+ }
3223
+ if (params.action === "status") {
3224
+ const left = estimandGaps(cwd, loadSpec(cwd), estimandRqs(cwd, ctx), estimandReport(cwd));
3225
+ return out(left.length ? `Still missing:\n- ${left.join("\n- ")}` : "The specification is complete: every estimand confirmed and recorded, and the report holds every number.");
3226
+ }
3227
+ const s = loadSpec(cwd);
3228
+ const id = String(params.id ?? "").trim();
3229
+ if (s && params.action === "confirm" && !id) {
3230
+ const ids = estimandsToConfirm(s);
3231
+ if (!ids.length)
3232
+ return out("Every estimand is confirmed.");
3233
+ const share = shellClock.budgetLeftShare();
3234
+ if (share !== undefined && share < 0.4) {
3235
+ const notes = ids.flatMap((x) => settleByRecommendation(s, x, "not put to the researcher because of the time limit"));
3236
+ saveSpec(cwd, s);
3237
+ return out([`${ids.join(", ")}: confirmed without asking (time budget nearly used).`, ...notes, "Run the analysis and record the results now; say in the report which choices the researcher did not see."].join("\n"));
3238
+ }
3239
+ return out([`Post the message below to the researcher as your whole reply, unchanged, then stop and wait. Record their reply with psyclaw_spec action=answers.`, "", estimandPlanMessage(s, ids)].join("\n"));
3240
+ }
3241
+ if (s && params.action === "answers") {
3242
+ const quote = String(params.quote ?? "").trim();
3243
+ if (!quote)
3244
+ throw new Error("answers needs quote: the researcher's reply, unchanged");
3245
+ const ids = estimandsToConfirm(s);
3246
+ const r = applyReply(s, ids, (params.answers ?? []), params.rest === "recommended" ? "recommended" : "open");
3247
+ saveSpec(cwd, s);
3248
+ for (const x of r.settled) {
3249
+ await recordSettled(cwd, { id: `${x.id}.${x.attr}`, question: `${x.id} ${ATTR_ZH[x.attr]}`, by: "researcher", choice: x.choice, quote, via: "text" }).catch(() => undefined);
3250
+ }
3251
+ const additions = (params.additions ?? []).map((a) => String(a).trim()).filter(Boolean);
3252
+ return out([
3253
+ ...r.notes,
3254
+ ...(additions.length ? [`The researcher wants these too: ${additions.join("; ")}. Add them as estimands (action=write, by "researcher" with their words) or to the shells, and report them.`] : []),
3255
+ r.left.length ? `Still unconfirmed: ${r.left.join(", ")}. Ask only what the reply left unclear (action=confirm id=…).` : "Every estimand is confirmed. Run the analysis now; do not ask the researcher again before the deliverables are done.",
3256
+ ].join("\n"));
3257
+ }
3258
+ const e = s?.estimands[id];
3259
+ if (!s || !e)
3260
+ throw new Error(`No estimand ${id || "(id missing)"}. Write the specification with action=write first.`);
3261
+ if (params.action === "waive") {
3262
+ if (String(params.reason ?? "").trim().length < 12)
3263
+ throw new Error("Give the reason it cannot be computed.");
3264
+ e.waived = String(params.reason).trim();
3265
+ saveSpec(cwd, s);
3266
+ return out(`Waived ${id}.`);
3267
+ }
3268
+ if (params.action === "record") {
3269
+ const msg = recordResult(cwd, s, id, params.values, String(params.evidence_file ?? ""));
3270
+ saveSpec(cwd, s);
3271
+ return out(msg);
3272
+ }
3273
+ // confirm: one choice box per open item, recommendation first so Enter takes it.
3274
+ if (e.confirmed_at && !estimandStale(e))
3275
+ return out(`${id} is already confirmed.`);
3276
+ if ((e.confirms ?? 0) >= MAX_CONFIRMS)
3277
+ throw new Error(`${id} was already put to the researcher ${MAX_CONFIRMS} times. Use your recommendation for what is still open (by "analyst" with the reason "the researcher did not choose") and go on.`);
3278
+ // Time budget: with under 40% left, settle the rest by recommendation so the analysis can run.
3279
+ const share = shellClock.budgetLeftShare();
3280
+ if (share !== undefined && share < 0.4) {
3281
+ const notes = settleByRecommendation(s, id, "not put to the researcher because of the time limit");
3282
+ saveSpec(cwd, s);
3283
+ return out([`${id}: confirmed without a card (time budget nearly used).`, ...notes, "Run the analysis and record the results now; say in the report which choices the researcher did not see."].join("\n"));
3284
+ }
3285
+ // The researcher's own words come first: no confirmation before they have answered once (in chat, or on a card).
3286
+ const userTurns = (() => {
3287
+ try {
3288
+ const branch = ctx.sessionManager?.getBranch?.() ?? [];
3289
+ // Only the researcher's own messages count, not PsyClaw's own nudges ("[psyclaw] ...").
3290
+ return branch.filter((entry) => {
3291
+ const m = entry.message;
3292
+ if (m?.role !== "user")
3293
+ return false;
3294
+ const c = m.content;
3295
+ const text = typeof c === "string" ? c : Array.isArray(c) ? c.map((x) => x.text ?? "").join("") : "";
3296
+ return !text.trimStart().startsWith("[psyclaw]");
3297
+ }).length;
3298
+ }
3299
+ catch {
3300
+ return 2;
3301
+ }
3302
+ })();
3303
+ const answeredOnCard = (await readDecisions(cwd).catch(() => [])).some((d) => d.by === "researcher");
3304
+ if (ctx.hasUI && userTurns < 2 && !answeredOnCard) {
3305
+ return out("Before the first confirmation, ask the researcher in chat, openly, how they planned to analyse each research question (sample, outcome coding, model, covariates, what to report), and stop until they answer. Then put their words into the specification (by \"researcher\" with the quote) and confirm what is still open.", true);
3306
+ }
3307
+ const items = cardItems(e);
3308
+ if (!ctx.hasUI) {
3309
+ return out(`No terminal to show the confirmation. Ask the researcher in chat, then write their answers with action=write (by "researcher", their words as the quote):\n${cardText(id, e, items)}`, true);
3310
+ }
3311
+ const card = `C${s.cards + 1}`;
3312
+ const answers = [];
3313
+ for (const it of items) {
3314
+ const title = it.attr === "report"
3315
+ ? `${id}(${e.rq})报告:${e.shell}`
3316
+ : `${id}(${e.rq})${e.quantity}\n${ATTR_ZH[it.attr]}:选一项(第一项是推荐)`;
3317
+ const order = it.attr === "report" ? [0] : [it.recommended - 1, ...it.options.map((_o, i) => i).filter((i) => i !== it.recommended - 1)];
3318
+ const labels = order.map((i, k) => `${it.options[i]}${k === 0 ? "(推荐)" : ""}`);
3319
+ const other = it.attr === "report" ? "还要补报别的(我来写)" : "别的做法(我来写)";
3320
+ const picked = await ctx.ui.select(title, [...labels, other], { timeout: 300_000 });
3321
+ if (picked === undefined) {
3322
+ answers.push({ kind: "none" });
3323
+ continue;
3324
+ }
3325
+ if (picked === other) {
3326
+ const text = (await ctx.ui.input(`${id} ${it.attr === "report" ? "还要报告什么" : ATTR_ZH[it.attr]}:写明你要的做法`, "", { timeout: 300_000 }))?.trim() ?? "";
3327
+ answers.push({ kind: "other", text });
3328
+ continue;
3329
+ }
3330
+ answers.push({ kind: "option", index: order[labels.indexOf(picked)] });
3331
+ }
3332
+ s.cards += 1;
3333
+ e.confirms = (e.confirms ?? 0) + 1;
3334
+ const notes = applyAnswers(s, id, card, items, answers);
3335
+ saveSpec(cwd, s);
3336
+ for (const [i, it] of items.entries()) {
3337
+ const a = answers[i];
3338
+ if (it.attr === "report" || !a || a.kind === "none")
3339
+ continue;
3340
+ const choice = a.kind === "option" ? it.options[a.index] : a.text || "(别的,没写明)";
3341
+ await recordSettled(cwd, { id: `${id}.${it.attr}`, question: `${id} ${ATTR_ZH[it.attr]}`, by: "researcher", choice, quote: choice, via: "terminal" }).catch(() => undefined);
3342
+ }
3343
+ return out(notes.join("\n"));
3344
+ }
3345
+ catch (error) {
3346
+ return out(error instanceof Error ? error.message : String(error), true);
3347
+ }
3348
+ },
3349
+ });
3350
+ pi.registerTool({
3351
+ name: "psyclaw_intent",
3352
+ label: "研究意图",
3353
+ description: "The researcher's intent, kept in the project (.psyclaw/intent.jsonl). Research mode, before the plan: first ask the researcher openly (no options) what they want to find out, what outcome matters most and how they planned to analyse it. Then action=restate with items (field question|outcome|approach|hypothesis|data|scope, optional label such as RQ1, text, and quote = their words or the materials' words unchanged; leave quote out for what you infer) and flow (theory: hypotheses first, then data; data: explore first, then literature). Code returns one message: post it as your whole reply and wait. When they reply, action=confirm with quote = the reply unchanged; if they correct something substantial, restate again. action=status shows the record. psyclaw_plan action=submit waits until the intent is confirmed.",
3354
+ parameters: Type.Object({
3355
+ action: Type.Union([Type.Literal("restate"), Type.Literal("confirm"), Type.Literal("status")]),
3356
+ items: Type.Optional(Type.Array(Type.Object({
3357
+ field: Type.String({ description: INTENT_FIELDS.join(" | ") }),
3358
+ label: Type.Optional(Type.String({ description: "Research-question label, e.g. RQ1 or H2" })),
3359
+ text: Type.String({ description: "The point, in research language" }),
3360
+ quote: Type.Optional(Type.String({ description: "The researcher's or the materials' words, unchanged; leave out for your inference" })),
3361
+ }))),
3362
+ flow: Type.Optional(Type.Union([Type.Literal("theory"), Type.Literal("data")])),
3363
+ quote: Type.Optional(Type.String({ description: "confirm: the researcher's reply, unchanged" })),
3364
+ corrections: Type.Optional(Type.String({ description: "confirm: their corrections, in their words" })),
3365
+ }),
3366
+ executionMode: "sequential",
3367
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
3368
+ try {
3369
+ if (params.action === "status") {
3370
+ const state = await readIntent(ctx.cwd);
3371
+ return { content: [{ type: "text", text: intentBrief(state) || "还没有复述过研究意图。" }], details: { version: state.current?.version ?? 0, confirmed: !!state.current?.confirmed } };
3372
+ }
3373
+ if (params.action === "confirm") {
3374
+ const { version } = await confirmIntent(ctx.cwd, params.quote ?? "", params.corrections);
3375
+ return { content: [{ type: "text", text: `研究意图 v${version} 已由研究者确认。${params.corrections?.trim() ? "Take their corrections into the plan. " : ""}Now build the plan against it: psyclaw_plan action=submit.` }], details: { version } };
3376
+ }
3377
+ const state = await readIntent(ctx.cwd);
3378
+ // Ask openly before restating: with only the brief on record, "how they planned to analyse it" would be a guess.
3379
+ if (ctx.hasUI && restoreSessionMode(ctx.sessionManager) === "research" && !state.current && state.said.length <= 1 && restateGateTries < 2) {
3380
+ restateGateTries += 1;
3381
+ return { content: [{ type: "text", text: "研究意图还没复述:研究者只发了任务说明。First ask them openly, with no options, in one message: what they most want to find out, the outcome that matters most, how they themselves planned to analyse it, and anything the brief leaves out. Restate after their answer." }], details: { status: "refused" }, isError: true };
3382
+ }
3383
+ const said = [state.said.map((x) => x.text).join("\n"), userTexts(ctx)].join("\n");
3384
+ const result = await restateIntent(ctx.cwd, { items: (params.items ?? []), ...(params.flow ? { flow: params.flow } : {}), materials: materialsText(ctx.cwd), said });
3385
+ if (result.problems.length) {
3386
+ return { content: [{ type: "text", text: ["研究意图还没记下:", ...result.problems.map((p) => `- ${p}`), "Fix these and restate again."].join("\n") }], details: { status: "refused" }, isError: true };
3387
+ }
3388
+ return {
3389
+ content: [{ type: "text", text: [`研究意图 v${result.version} 已记下。Post the message below to the researcher as your whole reply, unchanged, then stop and wait.`, "", renderIntent(result.items, params.flow)].join("\n") }],
3390
+ details: { version: result.version },
3391
+ };
3392
+ }
3393
+ catch (error) {
3394
+ return { content: [{ type: "text", text: `研究意图记录失败:${error instanceof Error ? error.message : String(error)}` }], details: { status: "failed" }, isError: true };
3395
+ }
3396
+ },
3397
+ });
3398
+ pi.registerTool({
3399
+ name: "psyclaw_plan",
3400
+ label: "分析方案",
3401
+ description: "The analysis plan for this project (research mode). action=submit records the proposal (primary outcome, primary analysis, methods, missing data, multiplicity, exclusions) with every decision point in `decisions`; code numbers them D1…Dn and returns one message for the researcher, which you post as your whole reply, then stop. action=answers records the researcher's one reply to that message (all points in one call) and approves the plan when they approved and nothing is left open. action=status shows the plan, its open decisions and what is missing. Running project scripts (other than explore/eda/profile/check ones) waits until the plan is approved.",
3402
+ parameters: Type.Object({
3403
+ action: Type.Union([Type.Literal("submit"), Type.Literal("answers"), Type.Literal("status"), Type.Literal("compare")]),
3404
+ goal: Type.Optional(Type.String({ description: "Research goal; used when no plan exists yet" })),
3405
+ decisions: Type.Optional(Type.Array(Type.Object({
3406
+ rq: Type.Optional(Type.String({ description: "Research-question label, e.g. RQ2" })),
3407
+ question: Type.String(),
3408
+ options: Type.Optional(Type.Array(Type.String())),
3409
+ recommended: Type.Optional(Type.Number({ description: "1-based index of your recommended option" })),
3410
+ by: Type.Optional(Type.Union([Type.Literal("open"), Type.Literal("brief"), Type.Literal("researcher"), Type.Literal("analyst")], { description: "open (default): the researcher decides; brief: the materials settle it (quote them); researcher: the researcher already said it (quote their words); analyst: a convention settles it (reason)" })),
3411
+ quote: Type.Optional(Type.String()),
3412
+ reason: Type.Optional(Type.String()),
3413
+ impact: Type.Optional(Type.Union([Type.Literal("key"), Type.Literal("intent"), Type.Literal("convention")], { description: "key: the choice changes the answer to a research question or the conclusion (at most 4 shown in full); intent: depends on what the researcher wants; convention: the field settles it" })),
3414
+ why: Type.Optional(Type.String({ description: "key points: one line on what changes in the result depending on the choice" })),
3415
+ }), { description: "submit: every decision point of the plan, per research question (sample and exclusions, outcome coding, contrast, summary measure, model, covariates and reference groups, missing data, intervals and multiplicity, what to report)" })),
3416
+ answers: Type.Optional(Type.Array(Type.Object({
3417
+ d: Type.String({ description: "The point, e.g. D3" }),
3418
+ option: Type.Optional(Type.Number({ description: "1-based option number the researcher picked" })),
3419
+ text: Type.Optional(Type.String({ description: "The researcher's own approach, in their words" })),
3420
+ }), { description: "answers: one entry per point the researcher's reply names" })),
3421
+ rest: Type.Optional(Type.Union([Type.Literal("recommended"), Type.Literal("open")], { description: "answers: recommended when the reply accepts the recommendations for the points it does not name (e.g. 全部按推荐, 其余同意, approve as proposed); open otherwise" })),
3422
+ approved: Type.Optional(Type.Boolean({ description: "answers: true when the reply approves the plan" })),
3423
+ quote: Type.Optional(Type.String({ description: "answers: the researcher's reply, unchanged" })),
3424
+ additions: Type.Optional(Type.Array(Type.String(), { description: "answers: analyses the researcher says the plan missed; they are added to the plan" })),
3425
+ agentAdditions: Type.Optional(Type.Array(Type.Object({ analysis: Type.String(), reason: Type.String() }), { description: "submit: analyses you add beyond what the brief and the researcher asked for, each with the reason; shown to the researcher as 我打算补的分析" })),
3426
+ checks: Type.Optional(Type.Array(Type.Object({
3427
+ d: Type.String({ description: "The label of what the researcher asked for (D3, A1, I1 …)" }),
3428
+ status: Type.Union([Type.Literal("done"), Type.Literal("changed"), Type.Literal("not-done")]),
3429
+ where: Type.Optional(Type.String({ description: "done: the script(s) or table(s) that show it, comma-separated, relative paths" })),
3430
+ evidence: Type.Optional(Type.String({ description: "done: words copied verbatim from that file that show it was done as decided (the code line, the column, the row)" })),
3431
+ to: Type.Optional(Type.String({ description: "changed: what was done instead" })),
3432
+ note: Type.Optional(Type.String({ description: "changed / not-done: why" })),
3433
+ }), { description: "compare: one check per item the researcher asked for" })),
3434
+ primaryOutcome: Type.Optional(Type.String()),
3435
+ primaryAnalysis: Type.Optional(Type.String()),
3436
+ proposedMethods: Type.Optional(Type.Array(Type.String())),
3437
+ exploratoryAnalyses: Type.Optional(Type.Array(Type.String())),
3438
+ missingDataPlan: Type.Optional(Type.String()),
3439
+ multiplicityPlan: Type.Optional(Type.String()),
3440
+ exclusionCriteria: Type.Optional(Type.String()),
3441
+ }),
3442
+ executionMode: "sequential",
3443
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
3444
+ try {
3445
+ let plan = await readActiveAnalysisPlan(ctx.cwd);
3446
+ if (params.action === "status") {
3447
+ if (!plan)
3448
+ return { content: [{ type: "text", text: "还没有分析方案。用 psyclaw_plan action=submit 提交。" }], details: { status: "none" } };
3449
+ const open = await openDecisions(ctx.cwd, plan.id);
3450
+ const findings = validateAnalysisPlan(plan).findings.map((f) => `- ${f.severity}: ${f.message}`);
3451
+ return { content: [{ type: "text", text: [formatAnalysisPlanStatus(plan, open.length), ...(findings.length ? ["缺口:", ...findings] : [])].join("\n") }], details: { planId: plan.id, status: plan.status } };
3452
+ }
3453
+ if (params.action === "compare") {
3454
+ // 做法对照 (practice.ts): what the researcher asked for against what was done, from the records.
3455
+ const intent = await readIntent(ctx.cwd).catch(() => undefined);
3456
+ const planDecisions = async () => (await readDecisions(ctx.cwd)).filter((d) => !plan || !d.planId || d.planId === plan.id);
3457
+ let decisions = await planDecisions();
3458
+ const checks = (params.checks ?? []);
3459
+ const rows = askedRows(decisions, intent);
3460
+ const problems = checkProblems(ctx.cwd, rows, checks);
3461
+ if (problems.length) {
3462
+ return { content: [{ type: "text", text: [
3463
+ "做法对照还没生成:", ...problems.map((p) => `- ${p}`), "",
3464
+ "Items the researcher asked for (use these labels):", ...rows.map((r) => `- ${r.label}: ${r.asked}`),
3465
+ "Give one check per item and call compare again.",
3466
+ ].join("\n") }], details: { status: "refused" }, isError: true };
3467
+ }
3468
+ for (const c of checks) {
3469
+ const row = rowFor(rows, c.d);
3470
+ if (c.status === "changed" && row?.decisionId)
3471
+ await recordDeviation(ctx.cwd, { id: row.decisionId, choice: c.to, reason: c.note, ...(plan ? { planId: plan.id } : {}) });
3472
+ }
3473
+ decisions = await planDecisions();
3474
+ const markdown = renderPractice(decisions, askedRows(decisions, intent), checks);
3475
+ mkdirSync(join(ctx.cwd, "analysis"), { recursive: true });
3476
+ writeFileSync(join(ctx.cwd, PRACTICE_PATH), markdown);
3477
+ return { content: [{ type: "text", text: [`已写入 ${PRACTICE_PATH}。Put this section at the top of the report, unchanged, and tell the researcher about every item under 我改的.`, "", markdown].join("\n") }], details: { path: PRACTICE_PATH } };
3478
+ }
3479
+ if (params.action === "answers") {
3480
+ if (!plan || !["awaiting-confirm", "ready", "reviewing"].includes(plan.status)) {
3481
+ return { content: [{ type: "text", text: `没有等研究者回复的方案(状态:${plan?.status ?? "无"})。` }], details: { status: plan?.status ?? "none" }, isError: true };
3482
+ }
3483
+ const quote = params.quote?.trim();
3484
+ if (!quote)
3485
+ throw new Error("answers needs quote: the researcher's reply, unchanged");
3486
+ const open = (await openDecisions(ctx.cwd, plan.id)).filter((d) => isPlanPointId(d.id));
3487
+ const { settle, left, problems } = settleFromReply(open, params.answers ?? [], params.rest ?? "open");
3488
+ for (const step of settle) {
3489
+ await recordSettled(ctx.cwd, { id: step.id, by: "researcher", choice: step.choice, quote, via: "text", planId: plan.id });
3490
+ }
3491
+ const additions = (params.additions ?? []).map((a) => a.trim()).filter(Boolean);
3492
+ if (additions.length) {
3493
+ plan = await writeAnalysisPlan(ctx.cwd, advanceAnalysisPlan(plan, { type: "draft", exploratoryAnalyses: [...(plan.exploratoryAnalyses ?? []), ...additions] }));
3494
+ // The researcher's own additions are decisions they made: they go into 做法对照 as 你要的.
3495
+ const prior = (await readDecisions(ctx.cwd)).filter((d) => new RegExp(`^${plan.id}:A\\d+$`).test(d.id)).length;
3496
+ for (const [k, a] of additions.entries()) {
3497
+ await recordSettled(ctx.cwd, { id: `${plan.id}:A${prior + k + 1}`, question: "研究者要补的分析", by: "researcher", choice: a, quote, via: "text", planId: plan.id });
3498
+ }
3499
+ }
3500
+ const stillOpen = await openDecisions(ctx.cwd, plan.id);
3501
+ const lines = [
3502
+ `记下 ${settle.length} 项(${settle.filter((x) => x.named).length} 项研究者点名,${settle.filter((x) => !x.named).length} 项按推荐)。`,
3503
+ ...(additions.length ? [`研究者要补的分析已加进方案:${additions.join(";")}。Run them and report them like the planned ones.`] : []),
3504
+ ...problems.map((p) => `- ${p}`),
3505
+ ];
3506
+ if (stillOpen.length) {
3507
+ lines.push(`还没定:${stillOpen.map((d) => `${pointLabel(d.id)}(${d.question})`).join(";")}。The reply leaves these unclear: ask only these, one psyclaw_ask card each (same id), then wait.`);
3508
+ if (left.length === 0 && problems.length === 0)
3509
+ lines.push("(这些不是本条方案消息里的点。)");
3510
+ return { content: [{ type: "text", text: lines.join("\n") }], details: { planId: plan.id, open: stillOpen.map((d) => d.id) } };
3511
+ }
3512
+ if (params.approved) {
3513
+ const status = await approvePlanFromCard(ctx.cwd);
3514
+ if (status === "running") {
3515
+ lines.push(`方案 ${plan.id} 已批准,开始执行。Run the analysis as decided now; do not ask the researcher again before the deliverables are done.`);
3516
+ return { content: [{ type: "text", text: lines.join("\n") }], details: { planId: plan.id, status } };
3517
+ }
3518
+ }
3519
+ lines.push("全部定下了。Ask the researcher to approve the plan with a plain yes (可以 / 批准), then stop.");
3520
+ return { content: [{ type: "text", text: lines.join("\n") }], details: { planId: plan.id, status: plan.status } };
3521
+ }
3522
+ if (!plan || plan.status === "completed") {
3523
+ plan = createAnalysisPlan({ goal: params.goal?.trim() || params.primaryAnalysis?.trim() || "analysis" });
3524
+ }
3525
+ if (plan.status === "running") {
3526
+ return { content: [{ type: "text", text: `方案 ${plan.id} 已批准并在执行。要改方案,先把改动告诉研究者;改了的决定用 psyclaw_decide 记录(同一个 id)。` }], details: { planId: plan.id, status: plan.status }, isError: true };
3527
+ }
3528
+ // The plan is built on the researcher's confirmed intent (intent.ts). Interactive sessions only;
3529
+ // after two refusals it goes through, with the gap stated.
3530
+ if (ctx.hasUI && restoreSessionMode(ctx.sessionManager) === "research") {
3531
+ const intent = await readIntent(ctx.cwd).catch(() => undefined);
3532
+ if (!intent?.current?.confirmed) {
3533
+ intentGateTries += 1;
3534
+ if (intentGateTries <= 2) {
3535
+ return { content: [{ type: "text", text: [
3536
+ "方案还没提交:研究者还没确认研究意图。",
3537
+ intent?.current
3538
+ ? `Restated intent v${intent.current.version} is waiting for the researcher's reply: wait for it, then psyclaw_intent action=confirm.`
3539
+ : "First ask the researcher openly (no options) what they want to find out, the outcome that matters most and how they planned to analyse it; then psyclaw_intent action=restate, post the message and wait.",
3540
+ ].join("\n") }], details: { planId: plan.id, status: plan.status, intent: "unconfirmed" }, isError: true };
3541
+ }
3542
+ }
3543
+ }
3544
+ // Decision coverage: each research question needs its analysis choices settled before the plan
3545
+ // goes to the researcher (the 11-29 PI run asked 4 cards for 5 RQs and scored lowest).
3546
+ // Asked twice already: let it through, with the gap stated.
3547
+ // The decision model may promote a convention to the researcher (never the reverse).
3548
+ const submitted = (params.decisions ?? []);
3549
+ const promote = new Set();
3550
+ if (decider.enabled) {
3551
+ for (const [i, p] of submitted.entries()) {
3552
+ if (p.by !== "analyst" || !p.reason?.trim())
3553
+ continue;
3554
+ const answers = await decider.ask("ask-researcher", { question: p.question, choice: p.options?.[(p.recommended ?? 1) - 1] ?? "", reason: p.reason }, { intent: ASK_RESEARCHER_QUESTION });
3555
+ if (DecisionModel.yesNo(answers?.intent) === true)
3556
+ promote.add(i);
3557
+ }
3558
+ }
3559
+ const numbered = numberPoints(plan.id, submitted, promote);
3560
+ // Quotes are checked against their source. by brief: the materials or a message (briefs are often pasted);
3561
+ // by researcher: their messages or their answers on cards (which live in the decision record).
3562
+ {
3563
+ const messages = [(await readIntent(ctx.cwd).catch(() => undefined))?.said.map((x) => x.text).join("\n") ?? "", userTexts(ctx)].join("\n");
3564
+ const answers = (await readDecisions(ctx.cwd).catch(() => [])).filter((d) => d.status === "settled" && d.by === "researcher").map((d) => `${d.choice ?? ""}\n${d.quote ?? ""}`).join("\n");
3565
+ const briefText = `${materialsText(ctx.cwd)}\n${messages}`;
3566
+ const researcherText = `${messages}\n${answers}`;
3567
+ submitted.forEach((p, i) => {
3568
+ const quote = p.quote?.trim();
3569
+ if (!quote || (p.by !== "brief" && p.by !== "researcher"))
3570
+ return;
3571
+ if (p.by === "brief" && !quoted(quote, briefText)) {
3572
+ numbered.problems.push(`point ${i + 1} (${p.question}): the quote is not found word for word in the materials or the messages.${quoted(quote, answers) ? " It is the researcher's answer on a card: use by researcher." : " Quote them exactly, or make the point open."}`);
3573
+ }
3574
+ if (p.by === "researcher" && !quoted(quote, researcherText)) {
3575
+ numbered.problems.push(`point ${i + 1} (${p.question}): the quote is not found word for word in the researcher's messages or answers. Quote them exactly, or make the point open.`);
3576
+ }
3577
+ });
3578
+ }
3579
+ if (numbered.problems.length) {
3580
+ return { content: [{ type: "text", text: ["方案还没提交:", ...numbered.problems.map((p) => `- ${p}`), "Fix these points and submit again."].join("\n") }], details: { planId: plan.id, status: plan.status }, isError: true };
3581
+ }
3582
+ const labels = researchQuestionLabels(`${materialsText(ctx.cwd)}\n${userTexts(ctx)}`);
3583
+ if (labels.length > 0) {
3584
+ const recorded = await readDecisions(ctx.cwd).catch(() => []);
3585
+ const text = (d) => JSON.stringify(d).toUpperCase().replace(/\s+/g, "");
3586
+ const all = [...recorded.filter((d) => !isPlanPointId(d.id)), ...numbered.points];
3587
+ const thin = labels.filter((label) => all.filter((d) => text(d).includes(label) || /ALLRQ|EVERYRQ|所有研究问题|全部研究问题/.test(text(d))).length < 3);
3588
+ planSubmitTries += 1;
3589
+ if (thin.length > 0 && planSubmitTries <= 2) {
3590
+ return { content: [{ type: "text", text: [
3591
+ `方案还没提交:这些研究问题的决定点少于 3 项:${thin.join("、")}。`,
3592
+ "For each of them, go through population (sample, exclusions, subgroups), outcome coding, contrast, summary measure, model, covariates and reference groups, missing data, and intervals / multiplicity.",
3593
+ "Put every one into `decisions` with its rq label (e.g. RQ2): open ones with options and your recommendation, brief-settled ones with by brief and the quote, conventions with by analyst and the reason. Then submit again.",
3594
+ ].join("\n") }], details: { planId: plan.id, status: plan.status, thin }, isError: true };
3595
+ }
3596
+ }
3597
+ plan = advanceAnalysisPlan(plan, {
3598
+ type: "draft",
3599
+ ...(params.primaryOutcome === undefined ? {} : { primaryOutcome: params.primaryOutcome }),
3600
+ ...(params.primaryAnalysis === undefined ? {} : { primaryAnalysis: params.primaryAnalysis }),
3601
+ ...(params.proposedMethods === undefined ? {} : { proposedMethods: params.proposedMethods }),
3602
+ ...(params.exploratoryAnalyses === undefined ? {} : { exploratoryAnalyses: params.exploratoryAnalyses }),
3603
+ ...(params.missingDataPlan === undefined ? {} : { missingDataPlan: params.missingDataPlan }),
3604
+ ...(params.multiplicityPlan === undefined ? {} : { multiplicityPlan: params.multiplicityPlan }),
3605
+ ...(params.exclusionCriteria === undefined ? {} : { exclusionCriteria: params.exclusionCriteria }),
3606
+ });
3607
+ plan = await writeAnalysisPlan(ctx.cwd, plan);
3608
+ if (numbered.points.length) {
3609
+ // A resubmission replaces the earlier numbering: points the researcher already settled keep their answer.
3610
+ const settledBefore = new Map((await readDecisions(ctx.cwd).catch(() => [])).filter((d) => d.status === "settled" && d.by === "researcher").map((d) => [d.id, d]));
3611
+ for (const p of numbered.points) {
3612
+ const options = p.options.map((label, i) => ({ id: String(i + 1), label }));
3613
+ const question = `${p.rq ? `${p.rq} ` : ""}${p.question}`;
3614
+ if (settledBefore.get(p.id)?.question === question)
3615
+ continue;
3616
+ if (!p.open) {
3617
+ await recordSettled(ctx.cwd, { id: p.id, question, by: p.by, choice: p.options[p.recommended - 1] ?? p.quote ?? p.reason, ...(p.quote ? { quote: p.quote } : {}), ...(p.reason ? { reason: p.reason } : {}), ...(p.by === "researcher" ? { via: "text" } : {}), options, planId: plan.id });
3618
+ }
3619
+ else {
3620
+ await recordAsked(ctx.cwd, { id: p.id, question, options, recommendation: p.options[p.recommended - 1], planId: plan.id, context: "plan-message" });
3621
+ }
3622
+ }
3623
+ const kept = new Set(numbered.points.map((p) => p.id));
3624
+ for (const d of await openDecisions(ctx.cwd, plan.id)) {
3625
+ if (isPlanPointId(d.id) && !kept.has(d.id))
3626
+ await recordSettled(ctx.cwd, { id: d.id, by: "analyst", choice: "(不再需要)", reason: "removed from the resubmitted plan", planId: plan.id });
3627
+ }
3628
+ const agentAdditions = (params.agentAdditions ?? []).map((a) => ({ analysis: a.analysis.trim(), reason: a.reason.trim() })).filter((a) => a.analysis && a.reason);
3629
+ for (const [k, a] of agentAdditions.entries()) {
3630
+ await recordSettled(ctx.cwd, { id: `${plan.id}:X${k + 1}`, question: "分析者补充的分析", by: "added", choice: a.analysis, reason: a.reason, planId: plan.id });
3631
+ }
3632
+ const message = renderPlanMessage(plan, numbered.points, agentAdditions);
3633
+ return {
3634
+ content: [{ type: "text", text: [
3635
+ `方案 ${plan.id} 已提交。Post the message below to the researcher as your whole reply, unchanged, then stop and wait. Do not ask cards before their reply.`,
3636
+ ...(numbered.promoted.length ? [`(${numbered.promoted.join(", ")} ${numbered.promoted.length === 1 ? "depends" : "depend"} on the researcher's intent, so ${numbered.promoted.length === 1 ? "it is" : "they are"} put to the researcher with your choice as the recommendation.)`] : []),
3637
+ "",
3638
+ message,
3639
+ ].join("\n") }],
3640
+ details: { planId: plan.id, status: plan.status, points: numbered.points.map((p) => p.id) },
3641
+ };
3642
+ }
3643
+ const open = await openDecisions(ctx.cwd, plan.id);
3644
+ const findings = validateAnalysisPlan(plan).findings.filter((f) => f.rule.startsWith("missing-")).map((f) => `- ${f.message}`);
3645
+ return {
3646
+ content: [{ type: "text", text: [
3647
+ `方案 ${plan.id} 已提交,等研究者批准。`,
3648
+ open.length ? `还有 ${open.length} 项决定待定:${open.map((d) => d.id).join("、")}。先用 psyclaw_ask 逐项问完。` : "没有待定的决定:请研究者看一下方案,回复「可以」即批准。",
3649
+ ...(findings.length ? ["还缺:", ...findings] : []),
3650
+ ].join("\n") }],
3651
+ details: { planId: plan.id, status: plan.status, open: open.map((d) => d.id) },
3652
+ };
3653
+ }
3654
+ catch (error) {
3655
+ return { content: [{ type: "text", text: `方案提交失败:${error instanceof Error ? error.message : String(error)}` }], details: { status: "failed" }, isError: true };
3656
+ }
3657
+ },
3658
+ });
3659
+ pi.registerTool({
3660
+ name: "psyclaw_decide",
3661
+ label: "记录决定",
3662
+ description: "Record a research decision in the project's one decision record (.psyclaw/decisions.jsonl; notes/decisions.md is written from it). Use it when the researcher answered in text instead of through psyclaw_ask (by=researcher, quote their words, reuse the id psyclaw_ask gave), when the materials settle a choice (by=brief, quote them), or when you settle it by a stated convention (by=analyst, give the reason). Answers given through psyclaw_ask are recorded by code; do not record them again. Call with action=list to see every decision and which are still open.",
3663
+ parameters: Type.Object({
3664
+ action: Type.Optional(Type.Union([Type.Literal("record"), Type.Literal("list"), Type.Literal("add"), Type.Literal("change")], { description: "record (default), list, add (an analysis you add beyond the request: question = the analysis, reason = why), or change (you change a decision the researcher or the brief settled: id, choice = what you do instead, reason = why; tell the researcher in your next message)" })),
3665
+ id: Type.Optional(Type.String({ description: "The decision id (from psyclaw_ask, or an earlier record) to settle or change" })),
3666
+ question: Type.Optional(Type.String({ description: "What was decided; required for a new decision" })),
3667
+ by: Type.Optional(Type.Union([Type.Literal("researcher"), Type.Literal("brief"), Type.Literal("analyst")])),
3668
+ choice: Type.Optional(Type.String({ description: "The decision itself" })),
3669
+ quote: Type.Optional(Type.String({ description: "by=researcher: the researcher's words, unchanged; by=brief: the words in the materials" })),
3670
+ reason: Type.Optional(Type.String({ description: "by=analyst: the convention followed and its source" })),
3671
+ context: Type.Optional(Type.String()),
3672
+ }),
3673
+ executionMode: "sequential",
3674
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
3675
+ try {
3676
+ if (params.action === "list") {
3677
+ const decisions = await readDecisions(ctx.cwd);
3678
+ return { content: [{ type: "text", text: formatDecisionsBrief(decisions) }], details: { decisions } };
3679
+ }
3680
+ const plan = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
3681
+ const planRef = plan && plan.status !== "completed" ? { planId: plan.id } : {};
3682
+ if (params.action === "add") {
3683
+ const analysis = (params.question ?? params.choice ?? "").trim();
3684
+ if (!analysis || !params.reason?.trim())
3685
+ throw new Error("add needs question (the analysis you add) and reason (why)");
3686
+ const event = await recordSettled(ctx.cwd, { question: "分析者补充的分析", by: "added", choice: analysis, reason: params.reason, ...planRef });
3687
+ return { content: [{ type: "text", text: `已记录 ${event.id}(我补的):${analysis}。It is listed under 我补的 in 做法对照.` }], details: { event } };
3688
+ }
3689
+ if (params.action === "change") {
3690
+ if (!params.id || !params.choice || !params.reason)
3691
+ throw new Error("change needs id, choice (what you do instead) and reason");
3692
+ const event = await recordDeviation(ctx.cwd, { id: params.id, choice: params.choice, reason: params.reason, ...planRef });
3693
+ return { content: [{ type: "text", text: `已记录改动 ${event.id}:${event.deviatesFrom?.choice} → ${event.choice}。Tell the researcher in your next message: what they decided, what you do instead and why; it stays under 我改的 until they settle it again.` }], details: { event } };
3694
+ }
3695
+ if (!params.by || !params.choice)
3696
+ throw new Error("record needs by and choice");
3697
+ const event = await recordSettled(ctx.cwd, {
3698
+ ...(params.id === undefined ? {} : { id: params.id }),
3699
+ ...(params.question === undefined ? {} : { question: params.question }),
3700
+ by: params.by,
3701
+ choice: params.choice,
3702
+ ...(params.quote === undefined ? {} : { quote: params.quote }),
3703
+ ...(params.reason === undefined ? {} : { reason: params.reason }),
3704
+ via: params.by === "researcher" ? "text" : undefined,
3705
+ ...planRef,
2794
3706
  ...(params.context === undefined ? {} : { context: params.context }),
2795
3707
  });
2796
- return { content: [{ type: "text", text: JSON.stringify(record, null, 2) }], details: record };
3708
+ const open = await openDecisions(ctx.cwd);
3709
+ // Only ever escalates: a decision the analyst settled that the model judges intent-dependent
3710
+ // gets a note to ask the researcher. It never cancels a question.
3711
+ let escalate = "";
3712
+ if (params.by === "analyst" && decider.enabled) {
3713
+ const answers = await decider.ask("ask-researcher", { question: event.question, choice: event.choice, reason: params.reason ?? "" }, { intent: ASK_RESEARCHER_QUESTION });
3714
+ if (DecisionModel.yesNo(answers?.intent) === true) {
3715
+ escalate = `\n[psyclaw] 这一项看起来取决于研究者的意图,不是惯例:请用 psyclaw_ask 问研究者(id ${event.id}),给出你的推荐。`;
3716
+ }
3717
+ }
3718
+ return {
3719
+ content: [{ type: "text", text: `已记录 ${event.id}:${event.question} → ${event.choice}${open.length ? `\n还有 ${open.length} 项待定:${open.map((d) => d.id).join("、")}` : ""}${escalate}` }],
3720
+ details: { event, open: open.map((d) => d.id) },
3721
+ };
2797
3722
  }
2798
3723
  catch (error) {
2799
- return { content: [{ type: "text", text: `选择记录失败:${error instanceof Error ? error.message : String(error)}` }], details: { status: "failed" }, isError: true };
3724
+ return { content: [{ type: "text", text: `决定记录失败:${error instanceof Error ? error.message : String(error)}` }], details: { status: "failed" }, isError: true };
2800
3725
  }
2801
3726
  },
2802
3727
  });
2803
3728
  pi.registerTool({
2804
- name: "psyclaw_wake_options",
2805
- label: "唤醒选项",
2806
- description: "向研究者弹出结构化选择或核对清单勾选(唤醒选项)。当用户在 Panel 中交互时优先弹窗;同时在 CLI 渲染同等选项。适用于:单选/多选决策、核对清单勾选、确认下一步。不要用自由文本「请回复选项编号」替代本工具。",
3729
+ name: "psyclaw_ask",
3730
+ label: "询问研究者",
3731
+ description: "Put one question to the researcher as a choice (or a checklist) in the terminal and the Panel. Code records the question and the answer in the project's decision record, so do not record it again. If the researcher does not answer here (no terminal, cancelled, timed out), the question stays open: ask in text and record their answer with psyclaw_decide using the returned id. Give a recommendation when you have one. Do not use free text like 'reply with an option number' instead of this tool.",
2807
3732
  parameters: Type.Object({
3733
+ id: Type.Optional(Type.String({ description: "Stable id for this decision; reuse it to ask about the same decision again" })),
3734
+ recommendation: Type.Optional(Type.String({ description: "The option you recommend and why, in one line" })),
2808
3735
  title: Type.String({ minLength: 1, description: "弹窗标题,例如「选择下一步」或「分析前核对」" }),
2809
3736
  prompt: Type.Optional(Type.String({ description: "可选说明文字" })),
2810
3737
  mode: Type.Union([Type.Literal("choice"), Type.Literal("checklist")], {
@@ -2824,16 +3751,45 @@ export default function psyclawExtension(pi) {
2824
3751
  executionMode: "sequential",
2825
3752
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
2826
3753
  try {
3754
+ // Research mode (11-29): analysis decisions go into the one plan message, not cards. While the restated
3755
+ // intent waits for the researcher, or after it is confirmed and before the plan is submitted, a choice
3756
+ // card is refused (three times at most); checklists and cards after the plan's reply stay allowed.
3757
+ if (ctx.hasUI && params.mode === "choice" && restoreSessionMode(ctx.sessionManager) === "research" && existsSync(join(ctx.cwd, ".psyclaw")) && askGateTries < 3) {
3758
+ const intent = await readIntent(ctx.cwd).catch(() => undefined);
3759
+ const pending = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
3760
+ const beforePlan = !pending || pending.status === "clarifying" || pending.status === "drafting" || pending.status === "completed";
3761
+ const reason = intent?.current && !intent.current.confirmed
3762
+ ? "The restated intent is waiting for the researcher's reply. Wait for it; if something is unclear, ask in your text reply, not on a card."
3763
+ : intent?.current?.confirmed && beforePlan
3764
+ ? "The intent is confirmed and the plan is not submitted yet: put this decision into the plan (psyclaw_plan action=submit, in decisions, with options and your recommendation). Cards are only for what the researcher's reply to the plan leaves unclear."
3765
+ : "";
3766
+ if (reason) {
3767
+ askGateTries += 1;
3768
+ return { content: [{ type: "text", text: `没有发卡片。${reason}` }], details: { status: "refused" }, isError: true };
3769
+ }
3770
+ }
3771
+ // An approval card is one decision: approve, or revise one element. Never a checklist.
3772
+ const approveOption = params.options.find((option) => /^approve$/i.test(option.id) || /^(批准|approve)\b/i.test(option.label));
3773
+ // A single choice always ends with "write my own": the researcher's plan may not be among the options.
3774
+ const mode = approveOption ? "choice" : params.mode;
3775
+ const OWN = "__own";
3776
+ const withOwn = mode === "choice" && !params.options.some((option) => option.id === OWN);
2827
3777
  const wakePrompt = buildWakePrompt({
2828
3778
  title: params.title,
2829
- mode: params.mode,
2830
- options: params.options.map((option) => ({
2831
- id: option.id,
2832
- label: option.label,
2833
- ...(option.description === undefined ? {} : { description: option.description }),
2834
- ...(option.checked === undefined ? {} : { checked: option.checked }),
2835
- })),
2836
- ...(params.prompt === undefined ? {} : { prompt: params.prompt }),
3779
+ mode,
3780
+ options: [
3781
+ ...params.options.map((option) => ({
3782
+ id: option.id,
3783
+ label: option.label,
3784
+ ...(option.description === undefined ? {} : { description: option.description }),
3785
+ ...(option.checked === undefined ? {} : { checked: option.checked }),
3786
+ })),
3787
+ ...(withOwn ? [{ id: OWN, label: "别的做法(我来写)" }] : []),
3788
+ ],
3789
+ // Show the recommendation in the box itself (the record keeps it as a separate field).
3790
+ ...(params.prompt === undefined && params.recommendation === undefined ? {} : {
3791
+ prompt: [params.prompt, params.recommendation ? `推荐:${params.recommendation}` : undefined].filter(Boolean).join("\n"),
3792
+ }),
2837
3793
  ...(params.allowMultiple === undefined ? {} : { allowMultiple: params.allowMultiple }),
2838
3794
  ...(params.minSelections === undefined ? {} : { minSelections: params.minSelections }),
2839
3795
  ...(params.syncVerify === undefined ? {} : { syncVerify: params.syncVerify }),
@@ -2842,12 +3798,26 @@ export default function psyclawExtension(pi) {
2842
3798
  if (wakePrompt.mode === "checklist") {
2843
3799
  await createWakeVerifyChecklist(ctx.cwd, wakePrompt);
2844
3800
  }
3801
+ const activePlan = await readActiveAnalysisPlan(ctx.cwd).catch(() => null);
3802
+ const planId = activePlan && activePlan.status !== "completed" ? activePlan.id : undefined;
3803
+ const asked = await recordAsked(ctx.cwd, {
3804
+ ...(params.id === undefined ? {} : { id: params.id }),
3805
+ question: [wakePrompt.title, params.prompt].filter(Boolean).join(":") || wakePrompt.title,
3806
+ options: wakePrompt.options.map((option) => ({
3807
+ id: option.id,
3808
+ label: option.label,
3809
+ ...(option.description === undefined ? {} : { description: option.description }),
3810
+ })),
3811
+ ...(params.recommendation === undefined ? {} : { recommendation: params.recommendation }),
3812
+ ...(planId ? { planId } : {}),
3813
+ });
3814
+ const stillOpen = `决定 ${asked.id} 仍待定:研究者没有在这里作答。请用文字问研究者,然后用 psyclaw_decide(id=${asked.id},by=researcher,quote=研究者原话)记录。`;
2845
3815
  const timeoutMs = Math.max(5_000, new Date(wakePrompt.expiresAt).getTime() - Date.now());
2846
3816
  const panelClients = panelHub.subscriberCount();
2847
3817
  if (ctx.hasUI) {
2848
3818
  ctx.ui.notify(panelClients > 0
2849
- ? `唤醒选项已推送到 Panel(${wakePrompt.title});CLI 也可作答`
2850
- : `唤醒选项:${wakePrompt.title}(Panel 未连接时仅 CLI)`, "info");
3819
+ ? `问题已推送到 Panel(${wakePrompt.title});终端里也可以作答`
3820
+ : `请作答:${wakePrompt.title}`, "info");
2851
3821
  }
2852
3822
  const panelPromise = waitForPanelWakeAnswer(wakePrompt, timeoutMs).then((answer) => ({ ...answer, raced: "panel" }));
2853
3823
  const cliPromise = (async () => {
@@ -2863,7 +3833,9 @@ export default function psyclawExtension(pi) {
2863
3833
  });
2864
3834
  return { promptId: wakePrompt.id, selectedIds: [], source: "cancel", raced: "cli" };
2865
3835
  }
2866
- const uiResult = await ctx.ui.custom((tui, theme, keybindings, done) => new WakeOptionsComponent(wakePrompt.title, wakePrompt.prompt, wakePrompt.mode, wakePrompt.options, Boolean(wakePrompt.allowMultiple), wakePrompt.minSelections ?? 0, tui, theme, keybindings, done), { overlay: true });
3836
+ const uiResult = await ctx.ui.custom((tui, theme, keybindings, done) => new WakeOptionsComponent(wakePrompt.title, wakePrompt.prompt, wakePrompt.mode, wakePrompt.options, Boolean(wakePrompt.allowMultiple), wakePrompt.minSelections ?? 0, tui, theme, keybindings, done,
3837
+ // Start on the recommended option, so Enter takes the recommendation.
3838
+ recommendedOptionIndex(wakePrompt.options, params.recommendation)), { overlay: true });
2867
3839
  if (!uiResult || uiResult.type === "cancel") {
2868
3840
  return { promptId: wakePrompt.id, selectedIds: [], source: "cancel", raced: "cli" };
2869
3841
  }
@@ -2881,13 +3853,13 @@ export default function psyclawExtension(pi) {
2881
3853
  }
2882
3854
  if (signal?.aborted) {
2883
3855
  return {
2884
- content: [{ type: "text", text: formatWakeResult({
3856
+ content: [{ type: "text", text: `${formatWakeResult({
2885
3857
  status: "cancelled",
2886
3858
  source: "cancel",
2887
3859
  selectedIds: [],
2888
3860
  selectedLabels: [],
2889
3861
  panelClients,
2890
- }) }],
3862
+ })}\n${stillOpen}` }],
2891
3863
  details: { status: "cancelled" },
2892
3864
  isError: true,
2893
3865
  };
@@ -2911,19 +3883,53 @@ export default function psyclawExtension(pi) {
2911
3883
  };
2912
3884
  if (result.status !== "answered") {
2913
3885
  return {
2914
- content: [{ type: "text", text: formatWakeResult(result) }],
2915
- details: result,
3886
+ content: [{ type: "text", text: `${formatWakeResult(result)}\n${stillOpen}` }],
3887
+ details: { ...result, decisionId: asked.id },
3888
+ isError: true,
3889
+ };
3890
+ }
3891
+ // "Write my own": ask for the researcher's words and record them as their answer.
3892
+ if (result.selectedIds.includes(OWN)) {
3893
+ const own = ctx.hasUI ? (await ctx.ui.input(`${wakePrompt.title}:写明你要的做法`, "", { timeout: 300_000 }))?.trim() : "";
3894
+ if (own) {
3895
+ await recordSettled(ctx.cwd, { id: asked.id, by: "researcher", choice: own, quote: own, via: "terminal", ...(planId ? { planId } : {}) });
3896
+ return {
3897
+ content: [{ type: "text", text: `研究者没有选列出的选项,写的是:「${own}」\n已记入决定 ${asked.id}。照研究者的原话做;原话没说清的地方再问。` }],
3898
+ details: { ...result, decisionId: asked.id, own },
3899
+ };
3900
+ }
3901
+ return {
3902
+ content: [{ type: "text", text: `研究者选了"别的做法"但没有写内容。决定 ${asked.id} 仍待定:用文字问研究者想怎么做,再用 psyclaw_decide(by=researcher)记录。` }],
3903
+ details: { ...result, decisionId: asked.id },
2916
3904
  isError: true,
2917
3905
  };
2918
3906
  }
3907
+ const choice = result.selectedLabels.join("; ") || (wakePrompt.mode === "checklist" ? "(一项都没勾)" : "");
3908
+ await recordSettled(ctx.cwd, {
3909
+ id: asked.id,
3910
+ by: "researcher",
3911
+ choice: [choice, result.notes].filter(Boolean).join(" — ") || "(未选择)",
3912
+ quote: [choice, result.notes].filter(Boolean).join(" — ") || "(未选择)",
3913
+ selectedIds: result.selectedIds,
3914
+ via: result.source === "panel" ? "panel" : "terminal",
3915
+ ...(planId ? { planId } : {}),
3916
+ });
3917
+ let planNote = "";
3918
+ if (approveOption && result.selectedIds.includes(approveOption.id)) {
3919
+ const status = await approvePlanFromCard(ctx.cwd);
3920
+ if (status === "running")
3921
+ planNote = "\n方案已批准,状态改为 running:现在执行正式分析。";
3922
+ else if (status === undefined && planId)
3923
+ planNote = "\n还有待定的决定,方案暂未改为 running:先逐项定完。";
3924
+ }
2919
3925
  return {
2920
- content: [{ type: "text", text: formatWakeResult(result) }],
2921
- details: result,
3926
+ content: [{ type: "text", text: `${formatWakeResult(result)}\n已记入决定 ${asked.id}。${planNote}` }],
3927
+ details: { ...result, decisionId: asked.id },
2922
3928
  };
2923
3929
  }
2924
3930
  catch (error) {
2925
3931
  return {
2926
- content: [{ type: "text", text: `唤醒选项失败:${error instanceof Error ? error.message : String(error)}` }],
3932
+ content: [{ type: "text", text: `询问失败:${error instanceof Error ? error.message : String(error)}` }],
2927
3933
  details: { status: "failed" },
2928
3934
  isError: true,
2929
3935
  };