psyclaw 0.33.1 → 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 (175) 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 +1497 -540
  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 -74
  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 -33
  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/orchestration/research-agents.js +1 -1
  59. package/dist/src/orchestration/research-agents.js.map +1 -1
  60. package/dist/src/orchestration/runner.d.ts +0 -1
  61. package/dist/src/orchestration/runner.js +0 -3
  62. package/dist/src/orchestration/runner.js.map +1 -1
  63. package/dist/src/orchestration/scheduler.js +0 -31
  64. package/dist/src/orchestration/scheduler.js.map +1 -1
  65. package/dist/src/panel/server.js +3 -4
  66. package/dist/src/panel/server.js.map +1 -1
  67. package/dist/src/project/hitl.js +3 -3
  68. package/dist/src/project/hitl.js.map +1 -1
  69. package/dist/src/project/workspace.js +8 -20
  70. package/dist/src/project/workspace.js.map +1 -1
  71. package/dist/src/research/decisions.d.ts +115 -0
  72. package/dist/src/research/decisions.js +284 -0
  73. package/dist/src/research/decisions.js.map +1 -0
  74. package/dist/src/research/intent.d.ts +90 -0
  75. package/dist/src/research/intent.js +175 -0
  76. package/dist/src/research/intent.js.map +1 -0
  77. package/dist/src/research/plan-message.d.ts +117 -0
  78. package/dist/src/research/plan-message.js +187 -0
  79. package/dist/src/research/plan-message.js.map +1 -0
  80. package/dist/src/research/practice.d.ts +33 -0
  81. package/dist/src/research/practice.js +160 -0
  82. package/dist/src/research/practice.js.map +1 -0
  83. package/dist/src/router/decision-model.d.ts +54 -0
  84. package/dist/src/router/decision-model.js +129 -0
  85. package/dist/src/router/decision-model.js.map +1 -0
  86. package/dist/src/rules/user-rules.js.map +1 -1
  87. package/dist/src/safety/data-access.js +4 -4
  88. package/dist/src/safety/data-access.js.map +1 -1
  89. package/dist/src/safety/secret-marks.d.ts +44 -0
  90. package/dist/src/safety/secret-marks.js +88 -0
  91. package/dist/src/safety/secret-marks.js.map +1 -0
  92. package/dist/src/session/continuously-work.js +1 -1
  93. package/dist/src/session/continuously-work.js.map +1 -1
  94. package/dist/src/session/help.js +29 -38
  95. package/dist/src/session/help.js.map +1 -1
  96. package/dist/src/session/modes.d.ts +24 -21
  97. package/dist/src/session/modes.js +81 -130
  98. package/dist/src/session/modes.js.map +1 -1
  99. package/dist/src/session/skill-invoke.d.ts +54 -0
  100. package/dist/src/session/skill-invoke.js +177 -0
  101. package/dist/src/session/skill-invoke.js.map +1 -0
  102. package/dist/src/session/skill-reference.d.ts +15 -0
  103. package/dist/src/session/skill-reference.js +35 -0
  104. package/dist/src/session/skill-reference.js.map +1 -0
  105. package/dist/src/skills/recommended.js +0 -2
  106. package/dist/src/skills/recommended.js.map +1 -1
  107. package/dist/src/skills/user-skills.js +11 -0
  108. package/dist/src/skills/user-skills.js.map +1 -1
  109. package/dist/src/style/cli-ui.js +15 -13
  110. package/dist/src/style/cli-ui.js.map +1 -1
  111. package/dist/src/tui/biosignal-wizard.js +1 -1
  112. package/dist/src/tui/biosignal-wizard.js.map +1 -1
  113. package/dist/src/tui/wake-options.d.ts +2 -2
  114. package/dist/src/tui/wake-options.js +8 -5
  115. package/dist/src/tui/wake-options.js.map +1 -1
  116. package/dist/src/updates/check.js +4 -2
  117. package/dist/src/updates/check.js.map +1 -1
  118. package/dist/src/updates/registry.d.ts +2 -1
  119. package/dist/src/updates/registry.js +2 -2
  120. package/dist/src/updates/registry.js.map +1 -1
  121. package/dist/src/updates/status.d.ts +9 -2
  122. package/dist/src/updates/status.js +43 -6
  123. package/dist/src/updates/status.js.map +1 -1
  124. package/dist/src/updates/update.js +7 -3
  125. package/dist/src/updates/update.js.map +1 -1
  126. package/dist/src/verify/checklist.d.ts +1 -1
  127. package/dist/src/verify/checklist.js +5 -5
  128. package/dist/src/verify/checklist.js.map +1 -1
  129. package/dist/src/wake-options/runtime.d.ts +9 -0
  130. package/dist/src/wake-options/runtime.js +39 -1
  131. package/dist/src/wake-options/runtime.js.map +1 -1
  132. package/dist/src/workflows/academic-export.js.map +1 -1
  133. package/dist/src/workflows/meta-analysis.js +1 -1
  134. package/dist/src/workflows/meta-analysis.js.map +1 -1
  135. package/package.json +2 -1
  136. package/skills/core/academic-grill/SKILL.md +3 -3
  137. package/skills/core/analysis-plan/SKILL.md +35 -32
  138. package/skills/core/manifest.json +12 -4
  139. package/skills/core/package-install/SKILL.md +35 -0
  140. package/skills/core/package-install/pkgnet.py +178 -0
  141. package/skills/recommended/mcp-catalog.json +1 -1
  142. package/dist/src/analysis/prior/apply.d.ts +0 -15
  143. package/dist/src/analysis/prior/apply.js +0 -98
  144. package/dist/src/analysis/prior/apply.js.map +0 -1
  145. package/dist/src/analysis/prior/checks.d.ts +0 -21
  146. package/dist/src/analysis/prior/checks.js +0 -233
  147. package/dist/src/analysis/prior/checks.js.map +0 -1
  148. package/dist/src/analysis/prior/constants.d.ts +0 -33
  149. package/dist/src/analysis/prior/constants.js +0 -117
  150. package/dist/src/analysis/prior/constants.js.map +0 -1
  151. package/dist/src/analysis/prior/gate.d.ts +0 -14
  152. package/dist/src/analysis/prior/gate.js +0 -93
  153. package/dist/src/analysis/prior/gate.js.map +0 -1
  154. package/dist/src/analysis/prior/memory.d.ts +0 -8
  155. package/dist/src/analysis/prior/memory.js +0 -46
  156. package/dist/src/analysis/prior/memory.js.map +0 -1
  157. package/dist/src/analysis/prior/reflect.d.ts +0 -6
  158. package/dist/src/analysis/prior/reflect.js +0 -48
  159. package/dist/src/analysis/prior/reflect.js.map +0 -1
  160. package/dist/src/analysis/prior/render.d.ts +0 -20
  161. package/dist/src/analysis/prior/render.js +0 -159
  162. package/dist/src/analysis/prior/render.js.map +0 -1
  163. package/dist/src/analysis/prior/submit.d.ts +0 -32
  164. package/dist/src/analysis/prior/submit.js +0 -213
  165. package/dist/src/analysis/prior/submit.js.map +0 -1
  166. package/dist/src/analysis/prior/tools.d.ts +0 -6
  167. package/dist/src/analysis/prior/tools.js +0 -38
  168. package/dist/src/analysis/prior/tools.js.map +0 -1
  169. package/dist/src/research/choice.d.ts +0 -16
  170. package/dist/src/research/choice.js +0 -25
  171. package/dist/src/research/choice.js.map +0 -1
  172. package/dist/src/skills/registry.d.ts +0 -28
  173. package/dist/src/skills/registry.js +0 -550
  174. package/dist/src/skills/registry.js.map +0 -1
  175. package/skills/core/prior-plan/SKILL.md +0 -53
@@ -1,17 +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 { priorToolBlock } from "../../analysis/prior/gate.js";
7
- import { readPriorMemory } from "../../analysis/prior/memory.js";
8
- import { priorApproved, priorPlanExists, priorRecallExists, recordPriorApproval } from "../../analysis/prior/submit.js";
9
- import { registerPriorTools } from "../../analysis/prior/tools.js";
10
- import { PSYCLAW_VERSION } from "../../branding.js";
12
+ import { PSYCLAW_BASIC_PROMPT, PSYCLAW_IDENTITY_PROMPT, PSYCLAW_VERSION, PSYCLAW_WRITING_RULES } from "../../branding.js";
11
13
  import { takeWhatsNew } from "../../updates/whats-new.js";
12
14
  import { formatDataAccess, loadDataAccess, redactScriptOnlyOutput, scriptOnlyBlock, setDataAccess } from "../../safety/data-access.js";
13
15
  import { Type } from "typebox";
14
- 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";
15
19
  import { parseInitArgs } from "./init-args.js";
16
20
  import { runPlanWithPi } from "../../orchestration/pi-executor.js";
17
21
  import { formatEffects, hasElevatedEffects, normalizeEffects, toolsForEffects } from "../../orchestration/effects.js";
@@ -26,30 +30,38 @@ import { lstat, mkdir, readFile } from "node:fs/promises";
26
30
  import { PROVIDER_PRESETS, providerCredentialSource, saveProviderConfig } from "../../setup.js";
27
31
  import { dirname } from "node:path";
28
32
  import { fileURLToPath } from "node:url";
29
- 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";
30
34
  import { buildRecommendedSkillInstallTask } from "../../skills/install-guidance.js";
31
35
  import { SkillManagerComponent } from "../../tui/skill-manager.js";
32
36
  import { BiosignalWizardComponent } from "../../tui/biosignal-wizard.js";
33
37
  import { readBiosignalPackCatalog, resolveBiosignalInstallPlan, } from "../../skills/biosignal-pack.js";
34
38
  import { WakeOptionsComponent } from "../../tui/wake-options.js";
35
- 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";
36
40
  import { panelHub } from "../../panel/hub.js";
37
- 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";
38
47
  import { enabledLocalSkillPaths, enabledLocalPromptPaths, readUserSkillState, scanLocalSkills, setLocalSkillEnabled, setLocalSkillsEnabled, skillNamesInPaths, userSkillId, } from "../../skills/user-skills.js";
39
48
  import { RuntimeMcpRegistry, setUserMcpConfigEnabled, } from "../../integrations/mcp-runtime.js";
40
49
  import { classifyIrreversibleHostCommand, extractToolCommandText, irreversibleHostBlockReason, } from "../../safety/irreversible-host-ops.js";
41
50
  import { SecretInputComponent, TextInputComponent, ProviderPickerComponent, } from "../../tui/provider-picker.js";
42
51
  import { resolveProviderBaseUrl } from "../../core/provider-endpoint.js";
43
- import { isArsPiActive, isArsPiTurn, psyclawArsPatch, setArsPiSessionActive, } from "../../ars/profile.js";
52
+ import { isArsPiActive, isArsPiTurn, psyclawArsPatch, setArsPiSessionActive } from "../../ars/profile.js";
44
53
  import { buildArsDoctorReport, ensurePdfEngineForExport } from "../../ars/doctor.js";
45
54
  import { formatAcademicSoftRouteInvocation, rankAcademicSoftRoutes, resolveAcademicSoftRoute, } from "../../ars/academic-router.js";
46
55
  import { advanceAnalysisPlan, createAnalysisPlan, formatAnalysisPlanStatus, readActiveAnalysisPlan, syncHandoffFromAnalysisPlan, writeAnalysisPlan, } from "../../analysis/plan.js";
47
- 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";
48
60
  import { composeMethodInjection, injectedTopicsFor, readSkillPreferences, referencedDocumentTopics, refreshSkillResolution, SKILL_RESOLUTION_ENTRY, userSkillsOutsideScriptOnly, writeSkillPreferences, } from "../../analysis/skill-resolution.js";
49
61
  import { formatAnalysisPlanTakeover, resolveStatsIntent, } from "../../analysis/stats-router.js";
50
62
  import { arsRoot } from "../../ars/pi-panel-executor.js";
51
63
  import { ArsModeEditor, isArsModeEditorText } from "../../ars/mode-editor.js";
52
- import { MODE_STATUS, detectChatModeMismatch, formatChatModeMismatchNotice, nextSessionMode, parseSessionMode, analysisFollowsPriorPrompt, sessionModePrompt, unattendedAnalysisPrompt, unattendedPriorPrompt, } from "../../session/modes.js";
64
+ import { MODE_STATUS, nextSessionMode, parseSessionMode, startingSessionMode, sessionModePrompt, unattendedAnalysisPrompt, } from "../../session/modes.js";
53
65
  import { continuouslyWorkWarningText, isContinuouslyWorkEnabled, } from "../../session/continuously-work.js";
54
66
  import { assertHumanVerifyGate, formatVerifyChecklist, isNaturalPlanConfirm, isPlanRitualConfirm, PLAN_RITUAL_PHRASE, ensureDefaultVerifyChecklist, loadVerifyChecklist, recordHumanVerification } from "../../verify/checklist.js";
55
67
  import { formatSessionHelp, formatSessionHelpBrief } from "../../session/help.js";
@@ -110,15 +122,7 @@ async function notifyAfterSkillChange(ctx, summary, level = "info") {
110
122
  return "manual-reload";
111
123
  }
112
124
  const activeAgentRuns = new Set();
113
- const CORE_SKILLS = new Set(["academic-grill", "research-intake", "evidence-capture", "citation-audit", "analysis-plan", "prior-plan"]);
114
- function findLastMatching(items, predicate) {
115
- for (let index = items.length - 1; index >= 0; index -= 1) {
116
- const item = items[index];
117
- if (item !== undefined && predicate(item))
118
- return item;
119
- }
120
- return undefined;
121
- }
125
+ const CORE_SKILLS = new Set(["academic-grill", "research-intake", "evidence-capture", "citation-audit", "analysis-plan"]);
122
126
  function coreSkillPath(name) {
123
127
  return join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..", "skills", "core", name, "SKILL.md");
124
128
  }
@@ -288,7 +292,7 @@ function academicGrillRequest(subject, mode) {
288
292
  /** Lightweight ideation path for research directions. */
289
293
  function academicBrainstormRequest(subject) {
290
294
  return [
291
- "这是 /brainstorm:做选题向头脑风暴。不要加载 academic-grill,不要进入逐题压力测试或研究规格访谈。",
295
+ "这是 /ars brainstorm:做选题向头脑风暴。不要加载 academic-grill,不要进入逐题压力测试或研究规格访谈。",
292
296
  subject
293
297
  ? `头脑风暴主题:${subject}`
294
298
  : "根据当前对话与项目材料确定头脑风暴主题;已有信息不要重复询问。",
@@ -685,7 +689,7 @@ async function showAgentManager(ctx, statusOnly = false) {
685
689
  const rows = await agentManagerRows(ctx.cwd);
686
690
  if (!ctx.hasUI || typeof ctx.ui.custom !== "function" || statusOnly) {
687
691
  ctx.ui.notify(rows.map((row) => `${row.status === "core" ? "◆" : "●"} ${row.id} — ${row.name}(${row.stage})`).join("\n")
688
- || "暂无 Subagent。可用 /create-subagent 创建(类似 Claude Code)。", "info");
692
+ || "暂无 Subagent。可用 /create subagent 创建(类似 Claude Code)。", "info");
689
693
  return;
690
694
  }
691
695
  while (true) {
@@ -890,7 +894,7 @@ function modelBiosignalPackInstallTask(root, plan, skillRows, mcpRows, mcpPlans,
890
894
  `研究域:${plan.domainNames.join("、")}(${plan.domainIds.join(", ")})`,
891
895
  `当前项目:${root}`,
892
896
  `Skill 安装位置:${skillScopeLabel(skillScope)}。`,
893
- "用户已通过 /biosignal 向导明确授权本次打包安装。你可以直接联网、克隆或下载来源、使用所需包管理器安装依赖、执行安装命令,并写入与清单有关的项目或用户级配置;不要再次要求用户批准这些安装步骤。",
897
+ "用户已通过 /mcp biosignal 向导明确授权本次打包安装。你可以直接联网、克隆或下载来源、使用所需包管理器安装依赖、执行安装命令,并写入与清单有关的项目或用户级配置;不要再次要求用户批准这些安装步骤。",
894
898
  "不要写入 data/raw、.git、凭据或符号链接目标。不要把模型口头声称当作完成证据;每个条目安装后检查目标目录或 MCP 配置是否存在。",
895
899
  "",
896
900
  "MCP 清单:",
@@ -899,7 +903,7 @@ function modelBiosignalPackInstallTask(root, plan, skillRows, mcpRows, mcpPlans,
899
903
  "Skill 清单:",
900
904
  ...(skillLines.length > 0 ? skillLines : ["(无)"]),
901
905
  "",
902
- "目录中的版本、命令和依赖只作参考;请先阅读各来源仓库的实际安装说明再落地。各项已在推荐状态中默认启用;全部完成后执行 /reload,并提醒用户:Shift+Tab 切到 analysis,用自然语言描述数据与分析目标即可开始。",
906
+ "目录中的版本、命令和依赖只作参考;请先阅读各来源仓库的实际安装说明再落地。各项已在推荐状态中默认启用;全部完成后执行 /reload,并提醒用户:在研究模式里用自然语言描述数据与分析目标即可开始。",
903
907
  "若某一条目安装命令本身失败,直接诊断并修复;只有遇到必须由用户提供的凭据或外部软件许可证时才向用户说明。",
904
908
  ].join("\n");
905
909
  }
@@ -972,7 +976,7 @@ async function queueBiosignalPackInstall(pi, ctx, plan, runtime) {
972
976
  return;
973
977
  await markBiosignalPackDesired(ctx.cwd, plan, scope);
974
978
  queueHiddenInstallTask(pi, ctx, modelBiosignalPackInstallTask(ctx.cwd, plan, skillRows, selectedMcp, mcpCatalog.installPrep, scope));
975
- ctx.ui.notify("已将生理信号能力包安装任务交给当前模型(指令不展示在对话中)。完成后请执行 /reload,并 Shift+Tab 切到 analysis 使用。", "info");
979
+ ctx.ui.notify("已将生理信号能力包安装任务交给当前模型(指令不展示在对话中)。完成后请执行 /reload,并在研究模式里使用。", "info");
976
980
  }
977
981
  async function showBiosignalPack(pi, ctx, runtime) {
978
982
  const catalog = await readBiosignalPackCatalog();
@@ -980,7 +984,7 @@ async function showBiosignalPack(pi, ctx, runtime) {
980
984
  const lines = [
981
985
  "生理信号分析能力包(无交互 UI 时仅列出研究域):",
982
986
  ...catalog.domains.map((domain) => `- ${domain.id}: ${domain.name} — ${domain.description}`),
983
- "请在交互式终端运行 /biosignal 完成选型与安装。",
987
+ "请在交互式终端运行 /mcp biosignal 完成选型与安装。",
984
988
  ];
985
989
  ctx.ui.notify(lines.join("\n"), "info");
986
990
  return;
@@ -1190,31 +1194,140 @@ export default function psyclawExtension(pi) {
1190
1194
  void initNodeObservability();
1191
1195
  const developerCommands = process.env.PSYCLAW_DEVELOPER_COMMANDS === "1";
1192
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
+ }
1193
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
+ };
1194
1282
  let arsModeEditor;
1195
1283
  let arsUiContext;
1196
- let sessionMode = "chat";
1284
+ let sessionMode = startingSessionMode(false);
1285
+ let startingMode;
1197
1286
  // Sticky mode as persisted on the session branch. Headless runs have no mode editor, so the input
1198
1287
  // handler must read it here too; otherwise a restored analysis session is treated as chat.
1199
1288
  const restoreSessionMode = (sessionManager) => {
1200
1289
  const modeEntry = [...(sessionManager?.getBranch?.() ?? [])].reverse().find((entry) => entry.type === "custom" && entry.customType === "psyclaw-session-mode");
1201
1290
  return parseSessionMode(modeEntry?.data?.mode)
1202
- ?? (isArsPiActive(sessionManager) ? "academic" : sessionMode);
1291
+ ?? startingMode ?? sessionMode;
1203
1292
  };
1204
1293
  let turnStartedAt;
1205
1294
  let llmTurnSpan;
1206
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
+ };
1207
1322
  const applySessionMode = (mode, opts) => {
1208
1323
  sessionMode = mode;
1324
+ syncModeTools(mode);
1209
1325
  arsModeEditor?.setMode(mode);
1210
1326
  arsUiContext?.ui.setStatus("mode", MODE_STATUS[mode]);
1211
1327
  // Clear legacy ars status key so it never duplicates with "mode".
1212
1328
  arsUiContext?.ui.setStatus("ars", undefined);
1213
1329
  if (opts?.syncSession === false || !arsUiContext)
1214
1330
  return;
1215
- setArsPiSessionActive(typeof pi.appendEntry === "function"
1216
- ? pi.appendEntry.bind(pi)
1217
- : undefined, mode === "academic");
1218
1331
  if (typeof pi.appendEntry === "function") {
1219
1332
  pi.appendEntry("psyclaw-session-mode", { mode });
1220
1333
  }
@@ -1222,11 +1335,11 @@ export default function psyclawExtension(pi) {
1222
1335
  const cycleSessionMode = () => {
1223
1336
  const next = nextSessionMode(arsModeEditor?.getMode() ?? sessionMode);
1224
1337
  applySessionMode(next);
1225
- arsUiContext?.ui.setStatus("mode", MODE_STATUS[next] ?? "chat");
1338
+ arsUiContext?.ui.setStatus("mode", MODE_STATUS[next]);
1226
1339
  };
1227
1340
  if (!legacyTestApi && typeof pi.registerShortcut === "function") {
1228
1341
  pi.registerShortcut("shift+tab", {
1229
- description: "Cycle chat → analysis → academic → prior",
1342
+ description: "Switch between basic mode and research mode",
1230
1343
  handler: () => {
1231
1344
  cycleSessionMode();
1232
1345
  },
@@ -1288,6 +1401,34 @@ export default function psyclawExtension(pi) {
1288
1401
  });
1289
1402
  if (!legacyTestApi && typeof pi.on === "function")
1290
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 */ }
1291
1432
  const fallback = ctxProviderModel(ctx);
1292
1433
  finishAgentSpan(llmTurnSpan, piTurnSpanAttributes(fallback));
1293
1434
  llmTurnSpan = undefined;
@@ -1313,32 +1454,31 @@ export default function psyclawExtension(pi) {
1313
1454
  pi.on("before_agent_start", async (event, ctx) => {
1314
1455
  const restored = restoreSessionMode(ctx?.sessionManager);
1315
1456
  sessionMode = restored;
1316
- const priorMemory = restored === "chat" || restored === "analysis"
1317
- ? await readPriorMemory(ctx?.cwd ?? process.cwd())
1318
- : "";
1319
- let modeBlock = sessionModePrompt(restored);
1320
- if (restored === "analysis" && ctx && !ctx.hasUI)
1457
+ syncModeTools(restored);
1458
+ let modeBlock = sessionModePrompt(restored, restored === "research" ? restoreStage(ctx?.sessionManager) : undefined);
1459
+ if (restored === "research" && ctx && !ctx.hasUI)
1321
1460
  modeBlock = `${modeBlock}\n\n${unattendedAnalysisPrompt()}`;
1322
- if (restored === "prior" && ctx && !ctx.hasUI)
1323
- modeBlock = `${modeBlock}\n\n${unattendedPriorPrompt()}`;
1324
- if (priorMemory && restored === "chat") {
1325
- modeBlock = `## PsyClaw mode: chat\nPlain assistant on the Pi harness. Follow the prior plan memory below for later analysis. Do not ask for a mode switch.\n\n${priorMemory}`;
1326
- }
1327
- if (priorMemory && restored === "analysis")
1328
- modeBlock = `${modeBlock}\n\n${analysisFollowsPriorPrompt(priorMemory)}`;
1329
- if (restored === "academic" || isArsPiTurn(event.systemPrompt) || isArsPiActive(ctx?.sessionManager)) {
1461
+ if (isArsPiTurn(event.systemPrompt) || isArsPiActive(ctx?.sessionManager)) {
1330
1462
  return {
1331
- 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({
1332
1464
  skills: event.systemPromptOptions?.skills,
1333
1465
  systemPrompt: event.systemPrompt,
1334
1466
  })}`,
1335
1467
  };
1336
1468
  }
1337
- 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}` };
1338
1474
  });
1339
1475
  if (!legacyTestApi && typeof pi.on === "function")
1340
1476
  pi.on("session_start", async (_event, ctx) => {
1341
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
+ }
1342
1482
  if (typeof ctx.cwd === "string") {
1343
1483
  try {
1344
1484
  const discovered = await refreshSkillResolution(ctx.cwd);
@@ -1371,6 +1511,8 @@ export default function psyclawExtension(pi) {
1371
1511
  ctx.ui.setEditorComponent((tui, theme, keybindings) => {
1372
1512
  const editor = new ArsModeEditor(tui, theme, keybindings);
1373
1513
  arsModeEditor = editor;
1514
+ editor.cwd = ctx.cwd;
1515
+ void loadDataAccess(ctx.cwd).then((loaded) => { editor.secretEntries = loaded.entries; }).catch(() => undefined);
1374
1516
  editor.onModeChange = (mode) => {
1375
1517
  sessionMode = mode;
1376
1518
  ctx.ui.setStatus("mode", MODE_STATUS[mode]);
@@ -1381,7 +1523,7 @@ export default function psyclawExtension(pi) {
1381
1523
  };
1382
1524
  const modeEntry = [...ctx.sessionManager.getBranch()].reverse().find((entry) => entry.type === "custom" && entry.customType === "psyclaw-session-mode");
1383
1525
  const restore = parseSessionMode(modeEntry?.data?.mode)
1384
- ?? (isArsPiActive(ctx.sessionManager) ? "academic" : "chat");
1526
+ ?? startingMode ?? sessionMode;
1385
1527
  editor.setMode(restore);
1386
1528
  sessionMode = restore;
1387
1529
  ctx.ui.setStatus("mode", MODE_STATUS[restore]);
@@ -1389,6 +1531,31 @@ export default function psyclawExtension(pi) {
1389
1531
  return editor;
1390
1532
  });
1391
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
+ });
1392
1559
  if (!legacyTestApi && typeof pi.on === "function")
1393
1560
  pi.on("input", async (event, ctx) => {
1394
1561
  if (event.source === "extension")
@@ -1415,14 +1582,26 @@ export default function psyclawExtension(pi) {
1415
1582
  }
1416
1583
  const mode = arsModeEditor?.getMode() ?? restoreSessionMode(ctx.sessionManager);
1417
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
+ }
1418
1597
  // A direct user statement is a valid human-review route when Panel is unavailable.
1419
1598
  // Do not infer approval from assistant output, quoted text, or a question about verification.
1420
1599
  if (/^我(?:已核验|已核实|已审阅并确认|核验了)(?:分析报告|论文定稿)?[。!!]?$/u.test(trimmed)) {
1421
1600
  const scope = trimmed.includes("论文定稿") ? "academic-finalize"
1422
1601
  : trimmed.includes("分析报告") ? "analysis-complete"
1423
- : mode === "academic" ? "academic-finalize" : mode === "analysis" ? "analysis-complete" : undefined;
1602
+ : "analysis-complete";
1424
1603
  if (!scope || !(await readActiveProject(ctx.cwd))) {
1425
- ctx.ui.notify("请先进入已初始化项目的 analysis 或 academic 模式,或明确说「我已核验分析报告」/「我已核验论文定稿」。", "warning");
1604
+ ctx.ui.notify("请先在已初始化的项目里操作,并明确说「我已核验分析报告」或「我已核验论文定稿」。", "warning");
1426
1605
  return { action: "handled" };
1427
1606
  }
1428
1607
  try {
@@ -1434,42 +1613,66 @@ export default function psyclawExtension(pi) {
1434
1613
  }
1435
1614
  return { action: "handled" };
1436
1615
  }
1437
- // Chat must not soft-takeover; when intent fits analysis/academic, remind only.
1438
- if (mode === "chat") {
1439
- const mismatch = detectChatModeMismatch(trimmed);
1440
- if (mismatch) {
1441
- 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) {
1442
1632
  return {
1443
1633
  action: "transform",
1444
- text: formatChatModeMismatchNotice(mismatch, trimmed),
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"),
1445
1639
  };
1446
1640
  }
1447
1641
  }
1448
- if (mode === "prior" && isPlanRitualConfirm(trimmed)) {
1449
- const result = await recordPriorApproval(ctx.cwd);
1450
- if (result.handoff)
1451
- applySessionMode("chat");
1452
- ctx.ui.notify(!result.handoff
1453
- ? result.message
1454
- : result.runFailed
1455
- ? "脚本已按确认结果改好,但执行失败。报错末尾在对话里,完整日志没有放进来。"
1456
- : "脚本已按确认结果改好并执行。当前是普通对话,可以使用 skill。", result.ok && !result.runFailed ? "info" : "warning");
1457
- return {
1458
- action: "transform",
1459
- text: !result.handoff
1460
- ? `User typed the approval phrase, but the prior plan is not ready. ${result.message} Do not execute.`
1461
- : result.runFailed
1462
- ? result.message
1463
- : `User approved the prior plan ("${PLAN_RITUAL_PHRASE}"). The script was updated from the confirmed choices and has already been run. ${result.message} The session is now plain chat. Skills may be used. Do not ask to switch modes and do not run the script again unless the researcher asks.`,
1464
- };
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) {
1649
+ return {
1650
+ action: "transform",
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"),
1656
+ };
1657
+ }
1465
1658
  }
1466
- // Plan confirmations: soft「可以」= per-node / method acknowledge; ritual phrase = authorize execute.
1467
- if (mode === "analysis" && (isPlanRitualConfirm(trimmed) || isNaturalPlanConfirm(trimmed))) {
1659
+ if (mode === "research" && approves) {
1468
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
+ }
1469
1671
  if (plan && (plan.status === "awaiting-confirm" || plan.status === "ready" || plan.status === "reviewing")) {
1470
1672
  const method = plan.confirmedMethod || plan.primaryAnalysis || plan.proposedMethods[0] || "按当前方案执行";
1471
- const pendingChoices = (plan.analysisChoices ?? []).filter((row) => !row.selected);
1472
- 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;
1473
1676
  if (!ritual) {
1474
1677
  // Soft acknowledge only — never jump to run-now.
1475
1678
  let next = plan.status === "awaiting-confirm" && !plan.confirmedMethod
@@ -1477,33 +1680,29 @@ export default function psyclawExtension(pi) {
1477
1680
  : plan;
1478
1681
  next = await writeAnalysisPlan(ctx.cwd, next);
1479
1682
  const needChoices = pendingChoices.length > 0
1480
- ? `仍有 ${pendingChoices.length} 项子分析待选;请先逐项确认。`
1481
- : `方法已记下。要开始执行,请完整输入:「${PLAN_RITUAL_PHRASE}」`;
1482
- 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");
1483
1686
  return {
1484
1687
  action: "transform",
1485
- text: [
1486
- "/skill:analysis-plan",
1487
- "",
1688
+ text: invokeSkill("analysis-plan", [
1488
1689
  `User soft-acknowledged ("${trimmed}"). Do NOT run scripts yet.`,
1489
1690
  `Confirmed method so far: ${next.confirmedMethod ?? method}`,
1490
1691
  pendingChoices.length > 0
1491
- ? `Pending per-analysis choices: ${pendingChoices.map((row) => row.id).join(", ")}. Present the next undecided choice card and wait.`
1492
- : `All listed choices are decided (or none yet). Ask the user to type exactly: ${PLAN_RITUAL_PHRASE}`,
1493
- "Do not start /crosscheck or /verify until the user explicitly agrees to open that block.",
1494
- ].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")),
1495
1696
  };
1496
1697
  }
1497
1698
  if (pendingChoices.length > 0) {
1498
- ctx.ui.notify(`${formatAnalysisPlanStatus(plan)}\n仪式句已收到,但还有 ${pendingChoices.length} 项子分析未确认,请先逐项选完。`, "warning");
1699
+ ctx.ui.notify(`${formatAnalysisPlanStatus(plan, pendingChoices.length)}\n已收到批准,但还有 ${pendingChoices.length} 项决定待定,请先逐项定完。`, "warning");
1499
1700
  return {
1500
1701
  action: "transform",
1501
- text: [
1502
- "/skill:analysis-plan",
1503
- "",
1504
- `User typed the ritual phrase but ${pendingChoices.length} analysis choice(s) remain undecided.`,
1505
- "Present the next undecided choice card and wait. Do not execute.",
1506
- ].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")),
1507
1706
  };
1508
1707
  }
1509
1708
  let next = plan.status === "awaiting-confirm"
@@ -1516,25 +1715,60 @@ export default function psyclawExtension(pi) {
1516
1715
  next = advanceAnalysisPlan(next, { type: "run-now" });
1517
1716
  next = await writeAnalysisPlan(ctx.cwd, next);
1518
1717
  if (next.status !== "running") {
1519
- ctx.ui.notify(`${formatAnalysisPlanStatus(next)}\n未能进入执行(检查子项确认与仪式批准)。`, "warning");
1718
+ ctx.ui.notify(`${formatAnalysisPlanStatus(next)}\n未能进入执行(检查子项是否都已确认)。`, "warning");
1520
1719
  return { action: "handled" };
1521
1720
  }
1522
- ctx.ui.notify(`${formatAnalysisPlanStatus(next)}\n已记录仪式批准并开始执行。`, "info");
1721
+ ctx.ui.notify(`${formatAnalysisPlanStatus(next)}\n已记录方案批准并开始执行。`, "info");
1523
1722
  return {
1524
1723
  action: "transform",
1525
- text: [
1526
- "/skill:analysis-plan",
1527
- "",
1528
- `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.`,
1529
1726
  `Confirmed method: ${next.confirmedMethod ?? method}`,
1530
- next.approvalMode === "auto" ? "approvalMode=auto: label outputs as 未经人审批." : "Human ritual approval recorded.",
1531
- "Do NOT auto-start /crosscheck or /verify. After scripts finish, ask whether to open those blocks; only proceed if the user agrees.",
1532
- ].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")),
1533
1769
  };
1534
1770
  }
1535
1771
  }
1536
- const wantsStats = mode === "analysis" && Boolean(resolveStatsIntent(trimmed));
1537
- const wantsAcademic = mode === "academic" && Boolean(resolveAcademicSoftRoute(trimmed));
1538
1772
  if ((wantsStats || wantsAcademic) && !(await readActiveProject(ctx.cwd))) {
1539
1773
  if (await hasCanonicalWorkspace(ctx.cwd)) {
1540
1774
  // Heal binding silently — prior /init layout already present.
@@ -1544,36 +1778,44 @@ export default function psyclawExtension(pi) {
1544
1778
  return {
1545
1779
  action: "transform",
1546
1780
  text: [
1547
- "尚未 /init。请先提醒用户初始化工作区;若用户确认可无仓继续,再处理其请求。",
1781
+ "No PsyClaw workspace here yet. Handle the request; mention once that /init sets up the research folders.",
1548
1782
  "User request:",
1549
1783
  trimmed,
1550
1784
  ].join("\n"),
1551
1785
  };
1552
1786
  }
1553
1787
  else {
1554
- const choice = await ctx.ui.select("尚未 /init。统计/写作建议先建仓,否则交接与核对清单不完整。", ["先执行 /init", "本次继续(稍后 init)", "取消"], { timeout: 120_000 });
1555
- if (choice === "取消" || choice === undefined)
1788
+ const choice = await ctx.ui.select("这个文件夹还没有研究工作区。要在这里建立吗?(data/、analysis/、literature/、paper/,原始数据只读保护)", ["在这里建立(推荐)", "不建,直接继续", "取消"], { timeout: 120_000 });
1789
+ if (choice === "取消")
1556
1790
  return { action: "handled" };
1557
- if (choice === "先执行 /init") {
1558
- 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");
1559
1796
  }
1560
- ctx.ui.notify("继续本次请求;建议随后 /init。关键结果请做交叉核验。", "warning");
1797
+ else if (choice !== undefined)
1798
+ ctx.ui.notify("继续本次请求;需要时可以用 /init 建立工作区。", "info");
1561
1799
  }
1562
1800
  }
1563
- if (mode === "academic") {
1564
- 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);
1565
1805
  if (!match)
1566
1806
  return;
1567
1807
  const ranked = rankAcademicSoftRoutes(event.text, 3);
1568
1808
  return {
1569
1809
  action: "transform",
1570
- text: formatAcademicSoftRouteInvocation(match, event.text, ranked.slice(1)),
1810
+ text: formatAcademicSoftRouteInvocation(match, event.text, ranked.slice(1), { skillLoaded: skillLoaded(branchOf(ctx), match.skill) }),
1571
1811
  };
1572
1812
  }
1573
- if (mode === "analysis") {
1813
+ {
1574
1814
  const userSkills = await userSkillsOutsideScriptOnly(ctx.cwd).catch(() => []);
1575
1815
  const userSkillNames = userSkills.map((skill) => skill.name);
1576
- 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 });
1577
1819
  const namesUserSkill = mentionsLoadedSkill(event.text, userSkillNames);
1578
1820
  // The task often lives in a document the message names ("Read BRIEF.md"), not in the message itself.
1579
1821
  const documents = namesUserSkill
@@ -1611,7 +1853,20 @@ export default function psyclawExtension(pi) {
1611
1853
  }
1612
1854
  catch { /* the process takeover still applies */ }
1613
1855
  if (match) {
1614
- 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 };
1615
1870
  }
1616
1871
  if (block)
1617
1872
  return { action: "transform", text: `${event.text.trim()}\n\n${block}` };
@@ -1620,13 +1875,146 @@ export default function psyclawExtension(pi) {
1620
1875
  });
1621
1876
  if (!legacyTestApi && typeof pi.on === "function")
1622
1877
  pi.on("context", (event) => {
1623
- const messages = maskToolObservationsStable(event.messages);
1878
+ const messages = maskHeavyParts(maskToolObservationsStable(event.messages));
1624
1879
  if (messages === event.messages)
1625
1880
  return;
1626
1881
  return { messages };
1627
1882
  });
1628
1883
  let dataAccessWarningShown = false;
1629
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
+ }
1630
2018
  if (!legacyTestApi && typeof pi.on === "function")
1631
2019
  pi.on("tool_call", async (event, ctx) => {
1632
2020
  // Host-teardown hard block runs even without /init — project approvals do not cover this.
@@ -1639,8 +2027,46 @@ export default function psyclawExtension(pi) {
1639
2027
  return { block: true, terminate: true, reason };
1640
2028
  }
1641
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);
1642
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
+ }
1643
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
+ }
1644
2070
  try {
1645
2071
  const access = await loadDataAccess(ctx.cwd);
1646
2072
  if (access.warning && !dataAccessWarningShown) {
@@ -1656,22 +2082,6 @@ export default function psyclawExtension(pi) {
1656
2082
  catch {
1657
2083
  // A broken checker must not take down unrelated tools. Defaults still apply on the next call.
1658
2084
  }
1659
- if (sessionMode === "prior") {
1660
- try {
1661
- const priorReason = priorToolBlock(sessionMode, event.toolName, event.input, {
1662
- recallReady: await priorRecallExists(ctx.cwd),
1663
- planReady: await priorPlanExists(ctx.cwd),
1664
- approved: await priorApproved(ctx.cwd),
1665
- });
1666
- if (priorReason) {
1667
- ctx.ui.notify(priorReason, "warning");
1668
- return { block: true, reason: priorReason };
1669
- }
1670
- }
1671
- catch {
1672
- // A broken prior gate must not take down unrelated tools.
1673
- }
1674
- }
1675
2085
  const run = await readActiveProject(ctx.cwd);
1676
2086
  if (!run || !toolNeedsApproval(event.toolName, event.input))
1677
2087
  return;
@@ -1721,10 +2131,14 @@ export default function psyclawExtension(pi) {
1721
2131
  const timedOutIndex = content.findIndex((part) => part.type === "text" && isShellTimeout(event.toolName, part.text));
1722
2132
  const timedOut = content[timedOutIndex];
1723
2133
  if (timedOut?.type === "text") {
1724
- content[timedOutIndex] = { ...timedOut, text: `${timedOut.text}\n${SHELL_TIMEOUT_HINT}` };
2134
+ content[timedOutIndex] = { ...timedOut, text: `${timedOut.text}\n${shellClock.timeoutHint(event.toolCallId)}` };
1725
2135
  changed = true;
1726
2136
  }
1727
- 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;
1728
2142
  const lastText = content.map((part) => part.type).lastIndexOf("text");
1729
2143
  const last = content[lastText];
1730
2144
  if (timing && last?.type === "text") {
@@ -1746,6 +2160,19 @@ export default function psyclawExtension(pi) {
1746
2160
  }
1747
2161
  }
1748
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
+ }
1749
2176
  if (!changed)
1750
2177
  return;
1751
2178
  return { content };
@@ -1776,21 +2203,23 @@ export default function psyclawExtension(pi) {
1776
2203
  ...(parsed.goal === undefined ? {} : { goal: parsed.goal }),
1777
2204
  ...(parsed.paradigm === undefined ? {} : { paradigm: parsed.paradigm }),
1778
2205
  });
2206
+ applySessionMode("research");
1779
2207
  if (already || hadProject) {
1780
2208
  ctx.ui.notify([
1781
2209
  `已检测到既有工作区,无需重新建仓:${project.id}`,
1782
- "规范目录与 psyclaw.md 已存在;跨会话可直接继续 analysis / academic。",
1783
- "Shift+Tab:chat → analysis → academic → prior · 输入 /help 查看速览。",
2210
+ "规范目录与 psyclaw.md 已存在;跨会话可直接继续分析或写作。",
2211
+ "还没想好研究问题?/ars brainstorm 一起想问题;/ars grill 把想法逐条问清楚。",
2212
+ "当前为研究模式;Shift+Tab 切换基础模式 / 研究模式。输入 /help 查看速览。",
1784
2213
  ].join("\n"), "info");
1785
2214
  return;
1786
2215
  }
1787
2216
  ctx.ui.notify([
1788
2217
  `工作仓库已初始化:${project.id}`,
1789
2218
  "已创建 data/raw|clean|secret、analysis/、literature/、paper/、psyclaw.md、.psyclaw/",
1790
- "data/secret 默认 script-only:模型不能直接读内容,分析脚本可以打开。/data-access 可改级别或指定其他文件。",
1791
- "Shift+Tab:chat → analysis → academic → prior",
1792
- "Thinking:Ctrl+Shift+T",
1793
- "prior 先回忆再出方案,确认后直接跑脚本并回到普通对话;analysis 仍可直接跑数;写作审稿切到 academic。输入 /help 查看速览。",
2219
+ "data/secret 默认 script-only:模型不能直接读内容,分析脚本可以打开。/secret 可改级别或指定其他文件。",
2220
+ "研究模式:分析、写作、审稿都在同一个对话里,按你说的事走对应流程。",
2221
+ "还没想好研究问题?/ars brainstorm 从数据里一起想几个可做的问题;/ars grill 把一个初步想法逐条问清楚。直接说“想用这份数据写文章”也会先走这一步。",
2222
+ "Shift+Tab:基础模式 / 研究模式 · Thinking:Ctrl+Shift+T · /help 查看速览。",
1794
2223
  ].join("\n"), "info");
1795
2224
  }
1796
2225
  catch (error) {
@@ -1798,23 +2227,40 @@ export default function psyclawExtension(pi) {
1798
2227
  }
1799
2228
  },
1800
2229
  });
1801
- pi.registerCommand("data-access", {
1802
- description: "查看或设置文件展示级别(full 或 script-only)",
2230
+ pi.registerCommand("secret", {
2231
+ description: "数据文件只许脚本读:/secret <文件> 设置,/secret off <文件> 取消,/secret list 查看全部;消息里写 @文件:s 也可以",
1803
2232
  handler: async (args, ctx) => {
1804
2233
  try {
1805
2234
  const parts = args.trim().split(/\s+/).filter(Boolean);
1806
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) {
1807
2242
  const loaded = await loadDataAccess(ctx.cwd);
1808
2243
  ctx.ui.notify([formatDataAccess(loaded.entries), loaded.warning].filter(Boolean).join("\n"), loaded.warning ? "warning" : "info");
1809
2244
  return;
1810
2245
  }
1811
- const access = parts.at(-1);
1812
- if (parts[0] !== "set" || parts.length < 3 || (access !== "full" && access !== "script-only")) {
1813
- 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");
1814
2256
  return;
1815
2257
  }
1816
- const entries = await setDataAccess(ctx.cwd, parts.slice(1, -1).join(" "), access);
1817
- 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");
1818
2264
  }
1819
2265
  catch (error) {
1820
2266
  await notifyError(ctx, error);
@@ -1828,13 +2274,14 @@ export default function psyclawExtension(pi) {
1828
2274
  if (!focus) {
1829
2275
  ctx.ui.notify([
1830
2276
  formatVerifyChecklist(await loadVerifyChecklist(ctx.cwd)),
1831
- "/crosscheck:过程性核对(数据、引文是否真实存在、格式/报告要求等)。",
1832
- "人审不经斜杠命令:收尾门禁会要求 Panel「核实」或唤醒选项。",
2277
+ "/check quick <焦点>:过程核对(数据、引文是否真实存在、格式/报告要求等)。",
2278
+ "/check full <焦点>:整体验证(分析结果是否成立、引文是否合理、方法是否合理)。",
2279
+ "人审不经斜杠命令:收尾门禁会要求 Panel「核实」或选择框。",
1833
2280
  ].join("\n"), "info");
1834
2281
  return;
1835
2282
  }
1836
2283
  pi.sendUserMessage([
1837
- "/crosscheck — 过程性交叉核对(AI)。",
2284
+ "/check quick — 过程性交叉核对(AI)。",
1838
2285
  `焦点:${focus}`,
1839
2286
  "范围重点:",
1840
2287
  "1) 数据与表:字段、N、表内数值与脚本/输出是否过程一致;",
@@ -1842,9 +2289,9 @@ export default function psyclawExtension(pi) {
1842
2289
  "3) 格式与报告要求:APA/三线表/必备报告字段、清单项是否齐;",
1843
2290
  "4) 过程产物:脚本入口、中间文件、可复现痕迹是否齐全。",
1844
2291
  "执行方式:派出至少两个独立审查视角(例如:数据一致性;引文存在性;格式/报告合同),各自给出发现后再合并为一份报告;标出一致项与冲突项。",
1845
- "不得自称已过人审。不要在用户未明确同意前自动启动本核对。人审由系统在交接/定稿门禁自动要求,经 Panel「核实」或唤醒选项完成。",
2292
+ "不得自称已过人审。不要在用户未明确同意前自动启动本核对。人审由系统在交接/定稿门禁自动要求,经 Panel「核实」或选择框完成。",
1846
2293
  ].join("\n"), ctx.isIdle() ? {} : { deliverAs: "followUp" });
1847
- ctx.ui.notify(`已启动过程性 /crosscheck(焦点:${focus})。大段核对应先征得用户同意。`, "info");
2294
+ ctx.ui.notify(`已启动过程核对 /check quick(焦点:${focus})。大段核对应先征得用户同意。`, "info");
1848
2295
  }
1849
2296
  catch (error) {
1850
2297
  await notifyError(ctx, error);
@@ -1857,13 +2304,13 @@ export default function psyclawExtension(pi) {
1857
2304
  if (!focus) {
1858
2305
  ctx.ui.notify([
1859
2306
  formatVerifyChecklist(await loadVerifyChecklist(ctx.cwd)),
1860
- "/verify:整体性验证(分析结果是否属实/成立、引文是否合理、方法是否合理)。",
1861
- "人审不经斜杠命令:Panel「核实」或唤醒选项。",
2307
+ "/check full <焦点>:整体验证(分析结果是否属实/成立、引文是否合理、方法是否合理)。",
2308
+ "人审不经斜杠命令:Panel「核实」或选择框。",
1862
2309
  ].join("\n"), "info");
1863
2310
  return;
1864
2311
  }
1865
2312
  pi.sendUserMessage([
1866
- "/verify — 整体性实质验证(AI)。",
2313
+ "/check full — 整体性实质验证(AI)。",
1867
2314
  `焦点:${focus}`,
1868
2315
  "范围重点:",
1869
2316
  "1) 分析结果是否属实、是否成立:效应方向/量级、不确定性、与脚本输出是否支持正文主张;",
@@ -1871,21 +2318,30 @@ export default function psyclawExtension(pi) {
1871
2318
  "3) 方法是否合理:设计、估计目标、检验/模型选择与研究问题是否匹配;",
1872
2319
  "4) 解释边界:相关≠因果、探索/确证区分、过度声称。",
1873
2320
  "给出可核对的判断(成立 / 存疑 / 不成立)及依据;不得自称已过人审。",
1874
- "人审由交接/定稿门禁自动要求,经 Panel「核实」或唤醒选项完成。",
2321
+ "人审由交接/定稿门禁自动要求,经 Panel「核实」或选择框完成。",
1875
2322
  ].join("\n"), ctx.isIdle() ? {} : { deliverAs: "followUp" });
1876
- ctx.ui.notify(`已启动整体性 /verify(焦点:${focus})。人审由收尾门禁自动要求。`, "info");
2323
+ ctx.ui.notify(`已启动整体验证 /check full(焦点:${focus})。人审由收尾门禁自动要求。`, "info");
1877
2324
  }
1878
2325
  catch (error) {
1879
2326
  await notifyError(ctx, error);
1880
2327
  }
1881
2328
  };
1882
- pi.registerCommand("crosscheck", {
1883
- description: "过程性 AI 核对:数据/引文真实性/格式要求;可附带焦点",
1884
- handler: async (args, ctx) => handleCrosscheck(args, ctx),
1885
- });
1886
- pi.registerCommand("verify", {
1887
- description: "整体性 AI 验证:结果是否成立、引文与方法是否合理;可附带焦点",
1888
- 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
+ },
1889
2345
  });
1890
2346
  pi.registerCommand("help", {
1891
2347
  description: "打开 Panel 使用速览",
@@ -1906,27 +2362,37 @@ export default function psyclawExtension(pi) {
1906
2362
  },
1907
2363
  });
1908
2364
  pi.registerCommand("plan", {
1909
- description: "分析方案:单独查看状态,或附带目标文本新建方案",
2365
+ description: "分析方案:/plan 查看状态,/plan <目标> 新建,/plan auto 不经人审批,/plan human 恢复人审",
1910
2366
  handler: async (args, ctx) => {
1911
2367
  try {
1912
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
+ }
1913
2381
  if (goal) {
1914
2382
  const plan = await writeAnalysisPlan(ctx.cwd, createAnalysisPlan({ goal }));
1915
2383
  ctx.ui.notify(`${formatAnalysisPlanStatus(plan)}\n已按目标创建。用自然语言确认方法(如「可以」);完成后用 /handoff 交接。`, "info");
1916
- pi.sendUserMessage([
1917
- "/skill:analysis-plan",
1918
- "",
2384
+ pi.sendUserMessage(invokeSkill("analysis-plan", [
1919
2385
  `Active plan ${plan.id} created for goal: ${goal}`,
1920
2386
  "Clarify methods with the researcher; prefer natural-language confirmation. Do not invent numbers.",
1921
- ].join("\n"), ctx.isIdle() ? {} : { deliverAs: "followUp" });
2387
+ ].join("\n"), skillLoaded(branchOf(ctx), "analysis-plan")), { expandPromptTemplates: true, ...(ctx.isIdle() ? {} : { deliverAs: "followUp" }) });
1922
2388
  return;
1923
2389
  }
1924
2390
  const plan = await readActiveAnalysisPlan(ctx.cwd);
1925
2391
  if (!plan) {
1926
- ctx.ui.notify("没有活跃分析 Plan。用 /plan <目标> 创建,或在 analysis 模式用自然语言触发 soft takeover。", "info");
2392
+ ctx.ui.notify("没有活跃分析 Plan。用 /plan <目标> 创建,或在研究模式里直接说要分析什么。", "info");
1927
2393
  return;
1928
2394
  }
1929
- 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");
1930
2396
  }
1931
2397
  catch (error) {
1932
2398
  await notifyError(ctx, error);
@@ -1944,7 +2410,7 @@ export default function psyclawExtension(pi) {
1944
2410
  }
1945
2411
  let plan = await readActiveAnalysisPlan(ctx.cwd);
1946
2412
  if (!plan) {
1947
- ctx.ui.notify("没有活跃分析 Plan,无法交接。先 /plan <目标> 或在 analysis 模式推进。", "warning");
2413
+ ctx.ui.notify("没有活跃分析 Plan,无法交接。先 /plan <目标>,或在研究模式里推进分析。", "warning");
1948
2414
  return;
1949
2415
  }
1950
2416
  const path = await syncHandoffFromAnalysisPlan(ctx.cwd, plan);
@@ -1954,193 +2420,189 @@ export default function psyclawExtension(pi) {
1954
2420
  : { type: "complete" });
1955
2421
  plan = await writeAnalysisPlan(ctx.cwd, plan);
1956
2422
  }
1957
- ctx.ui.notify(`${formatAnalysisPlanStatus(plan)}\n已写入 ${path}。可切到 academic 模式。`, "info");
2423
+ ctx.ui.notify(`${formatAnalysisPlanStatus(plan)}\n已写入 ${path}。可以接着写论文。`, "info");
1958
2424
  }
1959
2425
  catch (error) {
1960
2426
  await notifyError(ctx, error);
1961
2427
  }
1962
2428
  },
1963
2429
  });
1964
- if (!legacyTestApi)
1965
- pi.registerCommand("grill", {
1966
- description: "逐题追问并压力测试学术研究方案",
1967
- handler: async (args, ctx) => {
1968
- const subject = args.trim();
1969
- pi.sendUserMessage(academicGrillRequest(subject, "review"), ctx.isIdle() ? {} : { deliverAs: "followUp" });
1970
- ctx.ui.notify("已启动学术追问。完成后会先展示文档更新建议,并询问是否写回。", "info");
1971
- },
1972
- });
1973
- if (!legacyTestApi)
1974
- pi.registerCommand("brainstorm", {
1975
- description: "研究方向头脑风暴:提出并比较可选问题",
1976
- handler: async (args, ctx) => {
1977
- const subject = args.trim();
1978
- pi.sendUserMessage(academicBrainstormRequest(subject), ctx.isIdle() ? {} : { deliverAs: "followUp" });
1979
- ctx.ui.notify("已启动研究方向头脑风暴。", "info");
1980
- },
1981
- });
1982
- if (!legacyTestApi)
1983
- pi.registerCommand("review", {
1984
- description: "并发运行多角色模拟同行评审",
1985
- handler: async (_args, ctx) => {
1986
- if (activeAgentRuns.has(ctx.cwd)) {
1987
- 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");
1988
2457
  return;
1989
2458
  }
1990
- try {
1991
- const project = await readProject(ctx.cwd);
1992
- if (!(await readActiveProject(ctx.cwd))) {
1993
- ctx.ui.notify("请先使用 /init 初始化研究项目;未建仓时不会自动执行同行评审。", "warning");
1994
- return;
1995
- }
1996
- const reviewSkill = _args.trim();
1997
- activeAgentRuns.add(ctx.cwd);
1998
- ctx.ui.notify(`正在使用${reviewSkill?.trim() ? ` Skill“${reviewSkill.trim()}”辅助的` : "默认"} 4 角色并发模拟评审;不会自动改稿。`, "info");
1999
- const result = await runParallelPeerReview({
2000
- root: ctx.cwd,
2001
- project,
2002
- ...(ctx.model?.provider === undefined ? {} : { provider: ctx.model.provider }),
2003
- ...(ctx.model?.id === undefined ? {} : { model: ctx.model.id }),
2004
- env: providerEnvironment(ctx.model?.provider),
2005
- ...(reviewSkill ? { skillGuidance: reviewSkill } : {}),
2006
- onEvent: async (event) => { await new RunEventLog(ctx.cwd, event.runId).append(event); },
2007
- });
2008
- pi.appendEntry("psyclaw:multi-agent-review", {
2009
- runId: result.runId,
2010
- status: result.status,
2011
- outputPath: result.outputPath,
2012
- adoption: "review-output-only",
2013
- recordedAt: new Date().toISOString(),
2014
- });
2015
- ctx.ui.notify(`模拟审稿${result.status === "completed" ? "已完成" : "未完整完成"}:${result.outputPath}。审稿意见仅供研究者决定是否采纳。`, result.status === "completed" ? "info" : "warning");
2016
- }
2017
- catch (error) {
2018
- await notifyError(ctx, error);
2019
- }
2020
- finally {
2021
- 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");
2022
2498
  }
2023
- },
2024
- });
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
+ };
2025
2526
  if (!legacyTestApi)
2026
- pi.registerCommand("loop", {
2027
- description: "按计划循环推进当前研究阶段",
2527
+ pi.registerCommand("create", {
2528
+ description: "预览并创建项目级 skill、hook、rule 或 subagent:/create <种类> <名称与需求>",
2028
2529
  handler: async (args, ctx) => {
2029
- const requested = args.trim();
2030
- if (requested.toLowerCase() === "stop") {
2031
- if (ctx.isIdle())
2032
- ctx.ui.notify("当前没有正在运行的研究循环", "info");
2033
- else {
2034
- ctx.abort();
2035
- ctx.ui.notify("已请求停止当前研究循环", "warning");
2036
- }
2037
- return;
2038
- }
2039
- let project;
2040
- try {
2041
- project = await readProject(ctx.cwd);
2042
- }
2043
- catch {
2044
- ctx.ui.notify("请先使用 /init 初始化研究项目,再运行 /loop", "warning");
2045
- return;
2046
- }
2047
- if (!(await readActiveProject(ctx.cwd))) {
2048
- ctx.ui.notify("请先使用 /init 初始化研究项目,再运行 /loop。", "warning");
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");
2049
2535
  return;
2050
2536
  }
2051
- const objective = requested || project.goal;
2052
- const request = [
2053
- "运行一个有边界的 PsyClaw 研究循环,采用计划、执行、检查、修正的顺序推进当前研究阶段。",
2054
- `本轮目标:${objective}`,
2055
- "开始前读取 .psyclaw/project.json、notes/goal.md 和 notes/plan.md;如果当前对话或项目中存在经研究者确认的 /grill 研究规格,以该规格细化初始计划,但不得违反系统规则、AGENTS.md 或研究门禁。",
2056
- "先识别当前最高优先级且前提已满足的一个任务,再使用可用工具实际推进。不要只描述准备做什么。普通项目文件写入、脚本和可恢复工具调用在已 /init 的项目中连续推进;原始数据覆盖、凭据、外部发布、破坏性操作仍遵守单独的安全边界。",
2057
- "每完成一个实质步骤就检查产物、证据和计划是否一致。缺失信息若能检索、计算、重跑、改写或明确标注,应先自行修复。只有存在会改变研究问题、样本处理、操作化、估计目标、方法或解释的实质分歧时才请求研究者取舍;权限边界、不可恢复错误或当前阶段完成时停止。不得为了继续循环而虚构输入或结论。",
2058
- "本次最多推进一个可验收的研究阶段。结束时简要报告已完成、已核验、阻塞、计划变化和下一步;规划内容不得表述为已有研究证据。",
2059
- ].join("\n");
2060
- pi.sendUserMessage(request, ctx.isIdle() ? {} : { deliverAs: "followUp" });
2061
- ctx.ui.notify("已启动有界研究循环;使用 /loop stop 可请求中止", "info");
2537
+ pi.sendUserMessage(creationCommandPrompt(kind, requirements), ctx.isIdle() ? {} : { deliverAs: "followUp" });
2062
2538
  },
2063
2539
  });
2064
- for (const kind of ["skill", "hook", "rule", "subagent"]) {
2065
- if (!legacyTestApi)
2066
- pi.registerCommand(`create-${kind}`, {
2067
- description: `预览并创建项目级 ${kind}(附带名称与需求文本)`,
2068
- handler: async (args, ctx) => {
2069
- const requirements = args.trim();
2070
- if (!requirements) {
2071
- ctx.ui.notify(`请使用 /create-${kind} <名称与需求描述>`, "info");
2072
- return;
2073
- }
2074
- pi.sendUserMessage(creationCommandPrompt(kind, requirements), ctx.isIdle() ? {} : { deliverAs: "followUp" });
2075
- },
2076
- });
2077
- }
2078
2540
  if (!legacyTestApi)
2079
2541
  pi.registerCommand("skill", {
2080
- description: "打开 Skill 管理页",
2081
- handler: async (_args, ctx) => {
2082
- try {
2083
- await showSkillManager(pi, ctx);
2084
- }
2085
- catch (error) {
2086
- await notifyError(ctx, error);
2087
- }
2088
- },
2089
- });
2090
- if (!legacyTestApi)
2091
- pi.registerCommand("skill-preference", {
2092
- description: "查看或重置方法主题与用户 skill 的冲突选择",
2542
+ description: "打开 Skill 管理页;/skill preference [reset] 查看或重置方法主题的 skill 选择",
2093
2543
  handler: async (args, ctx) => {
2544
+ const [sub = "", ...rest] = args.trim().split(/\s+/);
2545
+ if (sub === "preference")
2546
+ return skillPreferenceHandler(rest.join(" "), ctx);
2094
2547
  try {
2095
- if (args.trim() === "reset") {
2096
- await writeSkillPreferences(ctx.cwd, { schemaVersion: "psyclaw/skill-preferences/v1", choices: {} });
2097
- ctx.ui.notify("已重置方法主题的 skill 选择。下次冲突会再问。", "info");
2098
- return;
2099
- }
2100
- const preferences = await readSkillPreferences(ctx.cwd);
2101
- const lines = Object.entries(preferences.choices);
2102
- ctx.ui.notify(lines.length === 0 ? "没有已保存的方法 skill 选择。" : lines.map(([key, value]) => `${key}: ${value}`).join("\n"), "info");
2103
- }
2104
- catch (error) {
2105
- await notifyError(ctx, error);
2106
- }
2107
- },
2108
- });
2109
- if (!legacyTestApi)
2110
- pi.registerCommand("biosignal", {
2111
- description: "生理信号分析能力包:选型研究域并安装 MCP/Skill",
2112
- handler: async (_args, ctx) => {
2113
- try {
2114
- await showBiosignalPack(pi, ctx, runtimeMcps);
2548
+ await showSkillManager(pi, ctx);
2115
2549
  }
2116
2550
  catch (error) {
2117
2551
  await notifyError(ctx, error);
2118
2552
  }
2119
2553
  },
2120
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
+ };
2121
2570
  if (!legacyTestApi)
2122
2571
  pi.registerCommand("ars", {
2123
- description: "学术模式:单独开启,或附带任务文本启动完整流程",
2572
+ description: "学术流程:/ars 开启,/ars stop 关闭,/ars <任务> 走完整流程;子命令 grill、brainstorm、review、loop",
2124
2573
  handler: async (args, ctx) => {
2125
2574
  try {
2126
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
+ }
2127
2588
  if (!trailing) {
2128
2589
  if (!ctx.hasUI) {
2129
- ctx.ui.notify("当前环境无编辑器;请改用 Shift+Tab 切换 academic。", "info");
2590
+ ctx.ui.notify("当前环境无编辑器;请直接用 /ars <任务> 启动学术流程。", "info");
2130
2591
  return;
2131
2592
  }
2132
2593
  arsUiContext = ctx;
2133
- applySessionMode("academic");
2594
+ setArsPiSessionActive(pi.appendEntry.bind(pi), true);
2595
+ ctx.ui.notify("已开启学术流程(ARS);/ars stop 关闭。", "info");
2134
2596
  return;
2135
2597
  }
2136
2598
  const lower = trailing.toLowerCase();
2137
2599
  if (lower === "stop") {
2138
2600
  arsUiContext = ctx;
2139
- applySessionMode("chat");
2601
+ setArsPiSessionActive(pi.appendEntry.bind(pi), false);
2140
2602
  if (ctx.hasUI && isArsModeEditorText(ctx.ui.getEditorText?.() ?? "")) {
2141
2603
  ctx.ui.setEditorText("");
2142
2604
  }
2143
- ctx.ui.notify("已回到 chat 模式", "info");
2605
+ ctx.ui.notify("已关闭学术流程(ARS)", "info");
2144
2606
  return;
2145
2607
  }
2146
2608
  if (lower === "doctor") {
@@ -2194,8 +2656,17 @@ export default function psyclawExtension(pi) {
2194
2656
  });
2195
2657
  if (!legacyTestApi)
2196
2658
  pi.registerCommand("mcp", {
2197
- description: "打开 MCP 安装与配置管理页",
2198
- 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
+ }
2199
2670
  try {
2200
2671
  await showMcpManager(pi, ctx, runtimeMcps);
2201
2672
  }
@@ -2333,187 +2804,69 @@ export default function psyclawExtension(pi) {
2333
2804
  }
2334
2805
  },
2335
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
+ };
2336
2842
  if (!legacyTestApi)
2337
- pi.registerCommand("pet", {
2338
- description: "启动横幅宠物:单独查看状态,或附带 on/off",
2339
- handler: async (args, ctx) => {
2340
- const action = args.trim().toLowerCase() || "status";
2341
- if (action === "status") {
2342
- ctx.ui.notify(`启动横幅宠物:${await petPreference() ? "已开启" : "已关闭(默认)"}`, "info");
2343
- return;
2344
- }
2345
- if (action !== "on" && action !== "off") {
2346
- ctx.ui.notify("请使用 /pet,或 /pet on|off", "error");
2347
- return;
2348
- }
2349
- await setPetPreference(action === "on");
2350
- ctx.ui.notify(`启动横幅宠物已${action === "on" ? "开启" : "关闭"},下次启动生效`, "info");
2351
- },
2352
- });
2353
- if (!legacyTestApi)
2354
- pi.registerCommand("telemetry", {
2355
- description: "查看或关闭匿名产品遥测",
2843
+ pi.registerCommand("prefs", {
2844
+ description: "偏好设置:/prefs pet [on|off] 启动横幅宠物,/prefs telemetry [on|off] 匿名产品遥测",
2356
2845
  handler: async (args, ctx) => {
2357
- const action = args.trim().toLowerCase() || "status";
2358
- if (action === "status") {
2359
- const preference = await readTelemetryPreference();
2360
- ctx.ui.notify(preference.enabled
2361
- ? "匿名产品遥测:开启(默认)。采集粗粒度使用与错误,不含研究正文。关闭:/telemetry off"
2362
- : "匿名产品遥测:已关闭。重新开启:/telemetry on", "info");
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");
2363
2853
  return;
2364
2854
  }
2365
- if (action !== "on" && action !== "off") {
2366
- ctx.ui.notify("Usage: /telemetry on|off|status", "error");
2367
- return;
2368
- }
2369
- await writeTelemetryPreference({ enabled: action === "on", noticeAcknowledged: true });
2370
- ctx.ui.notify(action === "on" ? "已开启匿名产品遥测。下次启动生效。" : "已关闭匿名产品遥测。下次启动不再发送。", "info");
2855
+ await petCommand.handler("", ctx);
2856
+ await telemetryCommand.handler("", ctx);
2371
2857
  },
2372
2858
  });
2373
2859
  if (typeof pi.registerTool === "function") {
2374
2860
  registerAnalysisRuntimeTools(pi);
2375
- registerPriorTools(pi, () => sessionMode);
2376
- pi.registerTool({
2377
- name: "psyclaw_research_decision",
2378
- label: "Research decision",
2379
- 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.",
2380
- parameters: Type.Object({
2381
- id: Type.String({ minLength: 1 }),
2382
- question: Type.String({ minLength: 1 }),
2383
- options: Type.Array(Type.Object({
2384
- id: Type.String({ minLength: 1 }),
2385
- label: Type.String({ minLength: 1 }),
2386
- rationale: Type.String({ minLength: 1 }),
2387
- consequences: Type.Array(Type.String()),
2388
- evidenceRefs: Type.Array(Type.String()),
2389
- }), { minItems: 2 }),
2390
- affectedAreas: Type.Array(Type.Union([
2391
- Type.Literal("research-question"),
2392
- Type.Literal("sample-treatment"),
2393
- Type.Literal("operationalization"),
2394
- Type.Literal("estimand"),
2395
- Type.Literal("analysis-method"),
2396
- Type.Literal("interpretation"),
2397
- ]), { minItems: 1 }),
2398
- evidenceCannotResolve: Type.Boolean(),
2399
- evidenceReviewed: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
2400
- methodsChecked: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
2401
- unresolvedReason: Type.String({ minLength: 1 }),
2402
- recommendation: Type.String({ minLength: 1 }),
2403
- }),
2404
- executionMode: "sequential",
2405
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
2406
- const run = await readActiveProject(ctx.cwd);
2407
- if (!run) {
2408
- return {
2409
- content: [{ type: "text", text: "当前目录尚未 /init,不能进入研究决策状态。请先执行 /init。" }],
2410
- details: { status: "general-mode" },
2411
- isError: true,
2412
- };
2413
- }
2414
- const request = {
2415
- schemaVersion: "psyclaw/research-decision/v1",
2416
- id: params.id,
2417
- question: params.question,
2418
- options: params.options,
2419
- affectedAreas: params.affectedAreas,
2420
- evidenceCannotResolve: params.evidenceCannotResolve,
2421
- evidenceReviewed: params.evidenceReviewed,
2422
- methodsChecked: params.methodsChecked,
2423
- unresolvedReason: params.unresolvedReason,
2424
- recommendation: params.recommendation,
2425
- };
2426
- try {
2427
- assertResearchDecision(request);
2428
- }
2429
- catch (error) {
2430
- return {
2431
- content: [{ type: "text", text: `该事项不符合研究取舍条件:${error instanceof Error ? error.message : String(error)}。请继续检索、计算、修复,或按单独的安全授权边界处理。` }],
2432
- details: { status: "not-a-research-decision", runId: run.runId },
2433
- isError: true,
2434
- };
2435
- }
2436
- const eventLog = new RunEventLog(ctx.cwd, run.runId);
2437
- const events = await eventLog.snapshot();
2438
- const resolvedIds = new Set(events
2439
- .filter((event) => event.type === "decision-resolved" && event.researchDecisionResolution)
2440
- .map((event) => event.researchDecisionResolution.decisionId));
2441
- const pending = findLastMatching(events, (event) => event.type === "awaiting-human" && Boolean(event.researchDecision && !resolvedIds.has(event.researchDecision.id)));
2442
- if (pending?.researchDecision) {
2443
- return {
2444
- content: [{ type: "text", text: `当前已有一项待研究者取舍的问题:${pending.researchDecision.question}。请先处理该问题,不能同时创建第二项。` }],
2445
- details: { status: "research-decision-already-pending", runId: run.runId, decisionId: pending.researchDecision.id },
2446
- isError: true,
2447
- };
2448
- }
2449
- if (events.some((event) => event.researchDecision?.id === request.id || event.researchDecisionResolution?.decisionId === request.id)) {
2450
- return {
2451
- content: [{ type: "text", text: `研究取舍编号已使用:${request.id}` }],
2452
- details: { status: "duplicate-research-decision", runId: run.runId, decisionId: request.id },
2453
- isError: true,
2454
- };
2455
- }
2456
- await eventLog.append({
2457
- type: "awaiting-human",
2458
- at: new Date().toISOString(),
2459
- researchDecision: request,
2460
- message: request.question,
2461
- });
2462
- return {
2463
- content: [{ type: "text", text: JSON.stringify({ status: "需要研究者取舍", runId: run.runId, decision: request }, null, 2) }],
2464
- details: { status: "awaiting-human", runId: run.runId, decisionId: request.id },
2465
- };
2466
- },
2467
- });
2468
- pi.registerTool({
2469
- name: "psyclaw_resolve_research_decision",
2470
- label: "Resolve research decision",
2471
- 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.",
2472
- parameters: Type.Object({
2473
- decisionId: Type.String({ minLength: 1 }),
2474
- selectedOption: Type.String({ minLength: 1 }),
2475
- rationale: Type.String({ minLength: 1 }),
2476
- }),
2477
- executionMode: "sequential",
2478
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
2479
- const run = await readActiveProject(ctx.cwd);
2480
- if (!run) {
2481
- return { content: [{ type: "text", text: "当前目录尚未 /init,没有有效的研究项目。" }], details: { status: "general-mode" }, isError: true };
2482
- }
2483
- const eventLog = new RunEventLog(ctx.cwd, run.runId);
2484
- const events = await eventLog.snapshot();
2485
- const resolvedIds = new Set(events
2486
- .filter((event) => event.type === "decision-resolved" && event.researchDecisionResolution)
2487
- .map((event) => event.researchDecisionResolution.decisionId));
2488
- const pending = findLastMatching(events, (event) => event.type === "awaiting-human" && event.researchDecision?.id === params.decisionId && !resolvedIds.has(params.decisionId));
2489
- if (!pending?.researchDecision) {
2490
- return { content: [{ type: "text", text: `未找到待处理的研究取舍:${params.decisionId}` }], details: { status: "not-found", runId: run.runId }, isError: true };
2491
- }
2492
- try {
2493
- const resolution = resolveResearchDecision(pending.researchDecision, {
2494
- selectedOption: params.selectedOption,
2495
- rationale: params.rationale,
2496
- });
2497
- await eventLog.append({ type: "decision-resolved", at: resolution.resolvedAt, researchDecisionResolution: resolution });
2498
- return {
2499
- content: [{ type: "text", text: JSON.stringify({ status: "executing", runId: run.runId, resolution }, null, 2) }],
2500
- details: { status: "executing", runId: run.runId, decisionId: resolution.decisionId },
2501
- };
2502
- }
2503
- catch (error) {
2504
- return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], details: { status: "invalid-resolution", runId: run.runId }, isError: true };
2505
- }
2506
- },
2507
- });
2508
2861
  pi.registerTool({
2509
2862
  name: "psyclaw_mcp",
2510
2863
  label: "MCP tools",
2511
- 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.",
2512
2865
  promptSnippet: "Discover and call enabled MCP servers such as MNE through PsyClaw.",
2513
2866
  parameters: Type.Object({
2514
2867
  action: Type.Union([Type.Literal("list"), Type.Literal("call")]),
2515
2868
  server: Type.Optional(Type.String({ description: "Configured MCP server id, for example mne-mcp" })),
2516
- 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)" })),
2517
2870
  input: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
2518
2871
  }),
2519
2872
  executionMode: "sequential",
@@ -2521,7 +2874,7 @@ export default function psyclawExtension(pi) {
2521
2874
  try {
2522
2875
  if (params.action === "list") {
2523
2876
  const servers = await runtimeMcps.list(ctx.cwd, params.server);
2524
- 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 } };
2525
2878
  }
2526
2879
  if (!(await readActiveProject(ctx.cwd))) {
2527
2880
  return {
@@ -2533,7 +2886,12 @@ export default function psyclawExtension(pi) {
2533
2886
  if (!params.server || !params.tool)
2534
2887
  throw new Error("server and tool are required for action=call");
2535
2888
  const result = await runtimeMcps.call(ctx.cwd, params.server, params.tool, params.input ?? {});
2536
- 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
+ };
2537
2895
  }
2538
2896
  catch (error) {
2539
2897
  return {
@@ -2653,25 +3011,44 @@ export default function psyclawExtension(pi) {
2653
3011
  });
2654
3012
  pi.registerTool({
2655
3013
  name: "psyclaw_skill",
2656
- label: "Research skill",
2657
- 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.",
2658
3016
  parameters: Type.Object({
2659
- name: Type.String({ description: "Core skill name: academic-grill, research-intake, evidence-capture, citation-audit, analysis-plan, or prior-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'" })),
2660
3021
  purpose: Type.Optional(Type.String({ description: "Short user-facing reason for using this skill now" })),
2661
3022
  }),
2662
3023
  executionMode: "sequential",
2663
3024
  async execute(_toolCallId, params) {
2664
- const name = params.name.trim();
2665
- 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) {
2666
3036
  return {
2667
- 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.` }],
2668
3038
  details: { status: "blocked", name },
2669
3039
  };
2670
3040
  }
2671
3041
  try {
2672
- 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");
2673
3050
  return {
2674
- 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}` }],
2675
3052
  details: { status: "active", name, ...(params.purpose === undefined ? {} : { purpose: params.purpose }) },
2676
3053
  };
2677
3054
  }
@@ -2701,7 +3078,7 @@ export default function psyclawExtension(pi) {
2701
3078
  const project = await readActiveProject(ctx.cwd);
2702
3079
  const softNote = project
2703
3080
  ? undefined
2704
- : "尚未 /init(软门禁):继续执行;收尾前须 AI /crosscheck 后人审。建议先 /init 建仓。";
3081
+ : "尚未 /init(软门禁):继续执行;收尾前须 AI /check quick 后人审。建议先 /init 建仓。";
2705
3082
  const request = params.request.trim();
2706
3083
  const combined = `${request} ${params.identifier ?? ""}`;
2707
3084
  const explicitWorkflow = params.workflow?.trim();
@@ -2820,40 +3197,541 @@ export default function psyclawExtension(pi) {
2820
3197
  },
2821
3198
  });
2822
3199
  pi.registerTool({
2823
- name: "psyclaw_record_choice",
2824
- label: "记录选择",
2825
- 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.",
2826
3203
  parameters: Type.Object({
2827
- prompt: Type.String({ minLength: 1, description: "当时向研究者提出的问题或选择提示" }),
2828
- originalResponse: Type.String({ minLength: 1, description: "研究者的原始回应,不能改写或省略" }),
2829
- selectedIds: Type.Array(Type.String(), { description: "解析后的选项 ID;无法明确解析时为空" }),
2830
- selectedLabels: Type.Array(Type.String(), { description: "解析后的选项名称" }),
2831
- source: Type.Union([Type.Literal("tool"), Type.Literal("free-text")]),
2832
- 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()),
2833
3214
  }),
2834
3215
  executionMode: "sequential",
2835
3216
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
3217
+ const out = (text, isError = false) => ({ content: [{ type: "text", text }], details: undefined, ...(isError ? { isError: true } : {}) });
2836
3218
  try {
2837
- const record = await appendChoiceRecord(ctx.cwd, {
2838
- prompt: params.prompt,
2839
- originalResponse: params.originalResponse,
2840
- selectedIds: params.selectedIds,
2841
- selectedLabels: params.selectedLabels,
2842
- 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,
2843
3706
  ...(params.context === undefined ? {} : { context: params.context }),
2844
3707
  });
2845
- 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
+ };
2846
3722
  }
2847
3723
  catch (error) {
2848
- 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 };
2849
3725
  }
2850
3726
  },
2851
3727
  });
2852
3728
  pi.registerTool({
2853
- name: "psyclaw_wake_options",
2854
- label: "唤醒选项",
2855
- 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.",
2856
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" })),
2857
3735
  title: Type.String({ minLength: 1, description: "弹窗标题,例如「选择下一步」或「分析前核对」" }),
2858
3736
  prompt: Type.Optional(Type.String({ description: "可选说明文字" })),
2859
3737
  mode: Type.Union([Type.Literal("choice"), Type.Literal("checklist")], {
@@ -2873,16 +3751,45 @@ export default function psyclawExtension(pi) {
2873
3751
  executionMode: "sequential",
2874
3752
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
2875
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);
2876
3777
  const wakePrompt = buildWakePrompt({
2877
3778
  title: params.title,
2878
- mode: params.mode,
2879
- options: params.options.map((option) => ({
2880
- id: option.id,
2881
- label: option.label,
2882
- ...(option.description === undefined ? {} : { description: option.description }),
2883
- ...(option.checked === undefined ? {} : { checked: option.checked }),
2884
- })),
2885
- ...(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
+ }),
2886
3793
  ...(params.allowMultiple === undefined ? {} : { allowMultiple: params.allowMultiple }),
2887
3794
  ...(params.minSelections === undefined ? {} : { minSelections: params.minSelections }),
2888
3795
  ...(params.syncVerify === undefined ? {} : { syncVerify: params.syncVerify }),
@@ -2891,12 +3798,26 @@ export default function psyclawExtension(pi) {
2891
3798
  if (wakePrompt.mode === "checklist") {
2892
3799
  await createWakeVerifyChecklist(ctx.cwd, wakePrompt);
2893
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=研究者原话)记录。`;
2894
3815
  const timeoutMs = Math.max(5_000, new Date(wakePrompt.expiresAt).getTime() - Date.now());
2895
3816
  const panelClients = panelHub.subscriberCount();
2896
3817
  if (ctx.hasUI) {
2897
3818
  ctx.ui.notify(panelClients > 0
2898
- ? `唤醒选项已推送到 Panel(${wakePrompt.title});CLI 也可作答`
2899
- : `唤醒选项:${wakePrompt.title}(Panel 未连接时仅 CLI)`, "info");
3819
+ ? `问题已推送到 Panel(${wakePrompt.title});终端里也可以作答`
3820
+ : `请作答:${wakePrompt.title}`, "info");
2900
3821
  }
2901
3822
  const panelPromise = waitForPanelWakeAnswer(wakePrompt, timeoutMs).then((answer) => ({ ...answer, raced: "panel" }));
2902
3823
  const cliPromise = (async () => {
@@ -2912,7 +3833,9 @@ export default function psyclawExtension(pi) {
2912
3833
  });
2913
3834
  return { promptId: wakePrompt.id, selectedIds: [], source: "cancel", raced: "cli" };
2914
3835
  }
2915
- 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 });
2916
3839
  if (!uiResult || uiResult.type === "cancel") {
2917
3840
  return { promptId: wakePrompt.id, selectedIds: [], source: "cancel", raced: "cli" };
2918
3841
  }
@@ -2930,13 +3853,13 @@ export default function psyclawExtension(pi) {
2930
3853
  }
2931
3854
  if (signal?.aborted) {
2932
3855
  return {
2933
- content: [{ type: "text", text: formatWakeResult({
3856
+ content: [{ type: "text", text: `${formatWakeResult({
2934
3857
  status: "cancelled",
2935
3858
  source: "cancel",
2936
3859
  selectedIds: [],
2937
3860
  selectedLabels: [],
2938
3861
  panelClients,
2939
- }) }],
3862
+ })}\n${stillOpen}` }],
2940
3863
  details: { status: "cancelled" },
2941
3864
  isError: true,
2942
3865
  };
@@ -2960,19 +3883,53 @@ export default function psyclawExtension(pi) {
2960
3883
  };
2961
3884
  if (result.status !== "answered") {
2962
3885
  return {
2963
- content: [{ type: "text", text: formatWakeResult(result) }],
2964
- 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 },
2965
3904
  isError: true,
2966
3905
  };
2967
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
+ }
2968
3925
  return {
2969
- content: [{ type: "text", text: formatWakeResult(result) }],
2970
- details: result,
3926
+ content: [{ type: "text", text: `${formatWakeResult(result)}\n已记入决定 ${asked.id}。${planNote}` }],
3927
+ details: { ...result, decisionId: asked.id },
2971
3928
  };
2972
3929
  }
2973
3930
  catch (error) {
2974
3931
  return {
2975
- content: [{ type: "text", text: `唤醒选项失败:${error instanceof Error ? error.message : String(error)}` }],
3932
+ content: [{ type: "text", text: `询问失败:${error instanceof Error ? error.message : String(error)}` }],
2976
3933
  details: { status: "failed" },
2977
3934
  isError: true,
2978
3935
  };