@oyasmi/pipiclaw 0.8.10-beta.1 → 0.8.10-beta.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 (38) hide show
  1. package/README.md +3 -3
  2. package/dist/index.d.ts +16 -34
  3. package/dist/index.js +14 -32
  4. package/dist/memory/maintenance-tuning.d.ts +37 -0
  5. package/dist/memory/maintenance-tuning.js +46 -0
  6. package/dist/memory/task-digest.js +2 -3
  7. package/dist/paths.d.ts +0 -1
  8. package/dist/paths.js +0 -1
  9. package/dist/playbooks/task-delegation.md +7 -13
  10. package/dist/playbooks/task-driving.md +0 -1
  11. package/dist/playbooks/task-planning.md +3 -5
  12. package/dist/runtime/bootstrap.d.ts +14 -0
  13. package/dist/runtime/bootstrap.js +8 -0
  14. package/dist/runtime/task-commands.js +34 -80
  15. package/dist/runtime/task-driver.js +3 -22
  16. package/dist/settings.d.ts +39 -30
  17. package/dist/settings.js +87 -83
  18. package/dist/shared/task-ledger.d.ts +8 -2
  19. package/dist/shared/task-ledger.js +9 -2
  20. package/dist/subagents/tool.d.ts +1 -5
  21. package/dist/subagents/tool.js +5 -107
  22. package/dist/tasks/control.d.ts +42 -23
  23. package/dist/tasks/control.js +61 -83
  24. package/dist/tasks/store.d.ts +0 -4
  25. package/dist/tasks/store.js +0 -46
  26. package/dist/tasks/verification.d.ts +10 -6
  27. package/dist/tasks/verification.js +0 -6
  28. package/dist/tools/memory-manage.js +46 -24
  29. package/dist/tools/registry.js +0 -2
  30. package/dist/tools/task-manage/create.js +1 -3
  31. package/dist/tools/task-manage/lifecycle.js +13 -34
  32. package/dist/tools/task-manage/schema.d.ts +0 -5
  33. package/dist/tools/task-manage/schema.js +1 -9
  34. package/dist/tools/task-manage/shared.d.ts +0 -3
  35. package/dist/tools/task-manage/shared.js +6 -68
  36. package/dist/tools/task-manage/types.d.ts +0 -2
  37. package/dist/tools/task-manage/verification.js +4 -4
  38. package/package.json +3 -1
package/README.md CHANGED
@@ -16,7 +16,7 @@ npm package: [`@oyasmi/pipiclaw`](https://www.npmjs.com/package/@oyasmi/pipiclaw
16
16
 
17
17
  **自己推进长程工作。** 定时事件支持立即、单次、周期三类,`preAction` 可用脚本做零 token 的触发前门控。语义更高一层的是任务台账(task ledger):任务以 Markdown 文件持久存在,内建 task driver 到点自动恢复、有进展有界续跑、停滞自动退避;配套受预算约束的恢复、独立验收、外部副作用授权,以及 `/tasks` 系列零 LLM 成本的控制面命令。
18
18
 
19
- **会用工具、能委派。** 内建 `bash`(支持 `async` 后台作业)、`read`(含目录树与 PDF)、`write` / `edit`、结构化 `grep`、`web_search` / `web_fetch`(结果缓存与分页续读),以及 `send_media`——生成好的报表、截图、导出文件可以作为原生附件直接发回钉钉,而不是丢给你一个打不开的主机路径。工作区配置的子代理可以把 reviewer、researcher 这类角色沉淀成可复用能力,支持 worktree 隔离与独立验收(verify);workspace skills 沉淀你自己的流程知识。完整清单见 [docs/tools.md](./docs/tools.md)。
19
+ **会用工具、能委派。** 内建 `bash`(支持 `async` 后台作业)、`read`(含目录树与 PDF)、`write` / `edit`、结构化 `grep`、`web_search` / `web_fetch`(结果缓存与分页续读),以及 `send_media`——生成好的报表、截图、导出文件可以作为原生附件直接发回钉钉,而不是丢给你一个打不开的主机路径。工作区配置的子代理可以把 reviewer、researcher 这类角色沉淀成可复用能力,支持独立验收(verify);workspace skills 沉淀你自己的流程知识。完整清单见 [docs/tools.md](./docs/tools.md)。
20
20
 
21
21
  **有安全护栏。** 所有文件、命令、网络工具都经过安全守卫:`bash` 命令拦截、统一路径检查、常见凭据与敏感位置默认拒绝、阻断写入审计日志;可通过 `security.json` 做实例级策略调整。详见 [docs/security.md](./docs/security.md)。
22
22
 
@@ -55,7 +55,7 @@ pipiclaw
55
55
  ├── channel.json # 钉钉应用配置
56
56
  ├── auth.json # 模型凭据
57
57
  ├── models.json # 自定义模型提供方
58
- ├── settings.json # 默认模型与运行时设置
58
+ ├── settings.json # 默认模型与模块开关
59
59
  ├── tools.json # 内建工具配置
60
60
  ├── security.json # 工具层安全策略
61
61
  └── workspace/ # 长期工作区:SOUL.md、AGENTS.md、MEMORY.md、
@@ -244,7 +244,7 @@ pipiclaw
244
244
  | [docs/memory.md](./docs/memory.md) | 记忆分层:它记得什么、怎么让它记住或忘掉 |
245
245
  | [docs/configuration.md](./docs/configuration.md) | 全部配置项:钉钉、模型、settings、tools、TUI、记忆与工作区文件 |
246
246
  | [docs/events-and-tasks.md](./docs/events-and-tasks.md) | 定时事件(含 `preAction` 门控、`event_manage`)、任务台账、内建 task driver、`/tasks` 控制面与 `task_manage` 工具 |
247
- | [docs/sub-agents.md](./docs/sub-agents.md) | 工作区配置子代理:委派、隔离 worktree 与独立验收 |
247
+ | [docs/sub-agents.md](./docs/sub-agents.md) | 工作区配置子代理:委派与独立验收 |
248
248
  | [docs/security.md](./docs/security.md) | 默认安全策略、`security.json` 配置与已知边界 |
249
249
  | [docs/deployment-and-operations.md](./docs/deployment-and-operations.md) | 长期运行、日志、可观测性、升级、备份与排障 |
250
250
  | [docs/scaling-and-concurrency.md](./docs/scaling-and-concurrency.md) | 并发模型与容量边界 |
package/dist/index.d.ts CHANGED
@@ -1,34 +1,16 @@
1
- export { COMMAND_RESULT_CUSTOM_TYPE, createCommandExtension, type PipiclawCommandExtensionOptions, } from "./agent/command-extension.js";
2
- export { type BuiltInCommand, type BuiltInCommandName, parseBuiltInCommand, renderBuiltInHelp, } from "./agent/commands.js";
3
- export { type AgentRunner, getOrCreateRunner } from "./agent/index.js";
4
- export { buildPipiclawSystemPrompt, RUNTIME_PROMPT_HARD_UNITS, RUNTIME_PROMPT_TARGET_UNITS, RUNTIME_PROMPT_VERSION, } from "./agent/prompt/builder.js";
5
- export { createPromptBoundaryExtension } from "./agent/prompt/extension.js";
6
- export { buildPromptManifest, type PromptManifest, renderContextReport } from "./agent/prompt/manifest.js";
7
- export { loadWorkspacePromptResources, type WorkspacePromptResources } from "./agent/prompt/resources.js";
8
- export { MAIN_PROMPT_SECTIONS } from "./agent/prompt/sections.js";
9
- export type { PromptAuthority, PromptBuildContext, PromptBuildResult, PromptCacheClass, PromptMode, PromptSectionDefinition, ResolvedPromptSection, ToolDescriptor, } from "./agent/prompt/types.js";
10
- export { loadPipiclawSkills, type PipiclawSkillsResult, resolvePipiclawSkills, } from "./agent/workspace-resources.js";
11
- export { createExecutor, type ExecOptions, type ExecResult, type Executor } from "./executor.js";
12
- export { type BuildMemoryCandidatesOptions, buildMemoryCandidates, createMemoryCandidateStore, type MemoryCandidate, type MemoryCandidateStore, } from "./memory/candidates.js";
13
- export { type ConsolidationRunOptions, type InlineConsolidationResult, runInlineConsolidation, } from "./memory/consolidation.js";
14
- export { ensureChannelMemoryFiles, ensureChannelMemoryFilesSync, getChannelSessionPath, readChannelSession, rewriteChannelSession, } from "./memory/files.js";
15
- export { type ConsolidationReason, MemoryLifecycle, type MemoryLifecycleOptions } from "./memory/lifecycle.js";
16
- export { type RecalledMemory, type RecallRequest, type RecallResult, recallRelevantMemory, } from "./memory/recall.js";
17
- export { renderSessionMemory, type SessionMemoryState, type SessionMemoryUpdateOptions, updateChannelSessionMemory, } from "./memory/session.js";
18
- export { runSidecarTask, type SidecarResult, type SidecarTask, } from "./memory/sidecar-worker.js";
19
- export { getApiKeyForModel } from "./models/api-keys.js";
20
- export { findExactModelReferenceMatch, findModelReferenceMatch, formatModelList, formatModelReference, resolveInitialModel, } from "./models/utils.js";
21
- export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, SUB_AGENTS_DIR, SUB_AGENTS_DIR_NAME, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
22
- export type { ChannelContext, ChannelContext as DingTalkContext, FinalDelivery, ProgressStyle, } from "./runtime/channel-context.js";
23
- export { ensureChannelDir, getChannelDir, getChannelDirName, } from "./runtime/channel-paths.js";
24
- export { createDingTalkContext } from "./runtime/delivery.js";
25
- export { type BusyMessageDefaultConfig, type BusyMessageMode, DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler, finalDeliveryOf, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, progressStyleOf, type ResponseMode, } from "./runtime/dingtalk.js";
26
- export { createEventsWatcher, type EventAction, EventsWatcher, type OneShotEvent, type PeriodicEvent, type ScheduledEvent, } from "./runtime/events.js";
27
- export { ChannelStore, type LoggedMessage, type LoggedSubAgentRun } from "./runtime/store.js";
28
- export { type PipiclawMemoryMaintenanceSettings, type PipiclawMemoryRecallSettings, type PipiclawSessionMemorySettings, type PipiclawSettings, PipiclawSettingsManager, } from "./settings.js";
29
- export { discoverSubAgents, formatSubAgentList, getSubAgentsDir, type ResolvedSubAgentConfig, resolveSubAgentConfig, type SubAgentConfig, type SubAgentContextMode, type SubAgentDiscoveryResult, type SubAgentInvocationOverrides, type SubAgentMemoryMode, type SubAgentToolName, } from "./subagents/discovery.js";
30
- export { createSubAgentTool, type SubAgentToolDetails, type SubAgentToolOptions, } from "./subagents/tool.js";
31
- export { DEFAULT_TOOLS_CONFIG, getToolsConfigPath, loadToolsConfig, type PipiclawToolsConfig, type PipiclawWebFetchConfig, type PipiclawWebSearchConfig, type PipiclawWebToolsConfig, } from "./tools/config.js";
32
- export { type CreatePipiclawToolsOptions, createPipiclawTools, } from "./tools/index.js";
33
- export { createUsageLedger, getUsageLedger, type UsageKind, type UsageLedger, type UsageLedgerEntry, type UsageSummary, } from "./usage/ledger.js";
34
- export { parseUsageMode, renderUsageReport, type UsageQueryMode, usageWindows } from "./usage/render.js";
1
+ /**
2
+ * Public API surface (spec 035 D4).
3
+ *
4
+ * Pipiclaw's product is the CLI/runtime, not an SDK. This barrel therefore
5
+ * supports exactly one use case — embedding the daemon in another process — and
6
+ * nothing else is a compatibility promise. Everything else is internal: import
7
+ * it from its module and expect it to move.
8
+ *
9
+ * Keep this list small. Every name added here also becomes a knip blind spot,
10
+ * because `src/index.ts` is a knip entry point.
11
+ */
12
+ export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
13
+ export { type AppContext, type BootstrapOptions, type BootstrapPaths, type BootstrapResult, bootstrap, isBootstrapExitError, } from "./runtime/bootstrap.js";
14
+ export type { ChannelContext, FinalDelivery, ProgressStyle } from "./runtime/channel-context.js";
15
+ export { DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler, type ResponseMode, } from "./runtime/dingtalk.js";
16
+ export type { PipiclawSettings } from "./settings.js";
package/dist/index.js CHANGED
@@ -1,32 +1,14 @@
1
- export { COMMAND_RESULT_CUSTOM_TYPE, createCommandExtension, } from "./agent/command-extension.js";
2
- export { parseBuiltInCommand, renderBuiltInHelp, } from "./agent/commands.js";
3
- export { getOrCreateRunner } from "./agent/index.js";
4
- export { buildPipiclawSystemPrompt, RUNTIME_PROMPT_HARD_UNITS, RUNTIME_PROMPT_TARGET_UNITS, RUNTIME_PROMPT_VERSION, } from "./agent/prompt/builder.js";
5
- export { createPromptBoundaryExtension } from "./agent/prompt/extension.js";
6
- export { buildPromptManifest, renderContextReport } from "./agent/prompt/manifest.js";
7
- export { loadWorkspacePromptResources } from "./agent/prompt/resources.js";
8
- export { MAIN_PROMPT_SECTIONS } from "./agent/prompt/sections.js";
9
- export { loadPipiclawSkills, resolvePipiclawSkills, } from "./agent/workspace-resources.js";
10
- export { createExecutor } from "./executor.js";
11
- export { buildMemoryCandidates, createMemoryCandidateStore, } from "./memory/candidates.js";
12
- export { runInlineConsolidation, } from "./memory/consolidation.js";
13
- export { ensureChannelMemoryFiles, ensureChannelMemoryFilesSync, getChannelSessionPath, readChannelSession, rewriteChannelSession, } from "./memory/files.js";
14
- export { MemoryLifecycle } from "./memory/lifecycle.js";
15
- export { recallRelevantMemory, } from "./memory/recall.js";
16
- export { renderSessionMemory, updateChannelSessionMemory, } from "./memory/session.js";
17
- export { runSidecarTask, } from "./memory/sidecar-worker.js";
18
- export { getApiKeyForModel } from "./models/api-keys.js";
19
- export { findExactModelReferenceMatch, findModelReferenceMatch, formatModelList, formatModelReference, resolveInitialModel, } from "./models/utils.js";
20
- export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, SUB_AGENTS_DIR, SUB_AGENTS_DIR_NAME, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
21
- export { ensureChannelDir, getChannelDir, getChannelDirName, } from "./runtime/channel-paths.js";
22
- export { createDingTalkContext } from "./runtime/delivery.js";
23
- export { DingTalkBot, finalDeliveryOf, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, progressStyleOf, } from "./runtime/dingtalk.js";
24
- export { createEventsWatcher, EventsWatcher, } from "./runtime/events.js";
25
- export { ChannelStore } from "./runtime/store.js";
26
- export { PipiclawSettingsManager, } from "./settings.js";
27
- export { discoverSubAgents, formatSubAgentList, getSubAgentsDir, resolveSubAgentConfig, } from "./subagents/discovery.js";
28
- export { createSubAgentTool, } from "./subagents/tool.js";
29
- export { DEFAULT_TOOLS_CONFIG, getToolsConfigPath, loadToolsConfig, } from "./tools/config.js";
30
- export { createPipiclawTools, } from "./tools/index.js";
31
- export { createUsageLedger, getUsageLedger, } from "./usage/ledger.js";
32
- export { parseUsageMode, renderUsageReport, usageWindows } from "./usage/render.js";
1
+ /**
2
+ * Public API surface (spec 035 D4).
3
+ *
4
+ * Pipiclaw's product is the CLI/runtime, not an SDK. This barrel therefore
5
+ * supports exactly one use case — embedding the daemon in another process — and
6
+ * nothing else is a compatibility promise. Everything else is internal: import
7
+ * it from its module and expect it to move.
8
+ *
9
+ * Keep this list small. Every name added here also becomes a knip blind spot,
10
+ * because `src/index.ts` is a knip entry point.
11
+ */
12
+ export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
13
+ export { bootstrap, isBootstrapExitError, } from "./runtime/bootstrap.js";
14
+ export { DingTalkBot, } from "./runtime/dingtalk.js";
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Cadence and threshold constants for the background memory maintenance
3
+ * pipeline (spec 035 D1/D2).
4
+ *
5
+ * These were `settings.json` keys until 0.8.10. They are algorithm parameters,
6
+ * not product intent: a user can decide *whether* background maintenance runs
7
+ * (`memoryMaintenance.enabled` is still a setting), but has no basis for
8
+ * deciding whether the checkpoint interval should be 20 minutes or 25.
9
+ */
10
+ export interface MemoryMaintenanceTuning {
11
+ /** How long a channel must be quiet before background LLM work is allowed. */
12
+ minIdleMinutesBeforeLlmWork: number;
13
+ sessionRefreshIntervalMinutes: number;
14
+ /** Idle cadence of the merged memory checkpoint (durable extraction) job. */
15
+ checkpointIntervalMinutes: number;
16
+ /** Confidence bar a candidate must clear before it is written to MEMORY.md. */
17
+ minMemoryAutoWriteConfidence: number;
18
+ structuralMaintenanceIntervalHours: number;
19
+ maxConcurrentChannels: number;
20
+ failureBackoffMinutes: number;
21
+ /** Reject a MEMORY.md cleanup whose result shrinks below this ratio of the original. */
22
+ cleanupShrinkGuardMinRatio: number;
23
+ /** Only apply the shrink guard when the original exceeds this length (chars). */
24
+ cleanupShrinkGuardMinChars: number;
25
+ }
26
+ export declare function getMemoryMaintenanceTuning(env?: NodeJS.ProcessEnv): MemoryMaintenanceTuning;
27
+ /**
28
+ * How much conversation must accumulate before a scheduled `SESSION.md` refresh
29
+ * is allowed (`maintenance-gates.ts` reads these). Constants like the tuning
30
+ * above, and lowered by the same test hook so a single-message E2E turn can
31
+ * trip the gate instead of waiting for a natural multi-turn exchange.
32
+ */
33
+ export interface SessionRefreshCadence {
34
+ minTurnsBetweenUpdate: number;
35
+ minToolCallsBetweenUpdate: number;
36
+ }
37
+ export declare function getSessionRefreshCadence(env?: NodeJS.ProcessEnv): SessionRefreshCadence;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Cadence and threshold constants for the background memory maintenance
3
+ * pipeline (spec 035 D1/D2).
4
+ *
5
+ * These were `settings.json` keys until 0.8.10. They are algorithm parameters,
6
+ * not product intent: a user can decide *whether* background maintenance runs
7
+ * (`memoryMaintenance.enabled` is still a setting), but has no basis for
8
+ * deciding whether the checkpoint interval should be 20 minutes or 25.
9
+ */
10
+ const PRODUCTION_TUNING = {
11
+ minIdleMinutesBeforeLlmWork: 10,
12
+ sessionRefreshIntervalMinutes: 10,
13
+ checkpointIntervalMinutes: 20,
14
+ minMemoryAutoWriteConfidence: 0.85,
15
+ structuralMaintenanceIntervalHours: 6,
16
+ maxConcurrentChannels: 1,
17
+ failureBackoffMinutes: 30,
18
+ cleanupShrinkGuardMinRatio: 0.4,
19
+ cleanupShrinkGuardMinChars: 2_000,
20
+ };
21
+ /**
22
+ * Test-only escape hatch. E2E and behavior-eval runs assert that `SESSION.md`
23
+ * refreshes within tens of seconds, which the production idle/interval gates
24
+ * make impossible. Set by `test/support/setup.ts`; deliberately undocumented in
25
+ * `docs/configuration.md` — it is a test hook, not a supported knob.
26
+ */
27
+ const FAST_MAINTENANCE_TUNING = {
28
+ ...PRODUCTION_TUNING,
29
+ minIdleMinutesBeforeLlmWork: 0,
30
+ sessionRefreshIntervalMinutes: 0,
31
+ failureBackoffMinutes: 1,
32
+ };
33
+ export function getMemoryMaintenanceTuning(env = process.env) {
34
+ return env.PIPICLAW_TEST_FAST_MAINTENANCE === "1" ? FAST_MAINTENANCE_TUNING : PRODUCTION_TUNING;
35
+ }
36
+ const PRODUCTION_SESSION_REFRESH = {
37
+ minTurnsBetweenUpdate: 2,
38
+ minToolCallsBetweenUpdate: 4,
39
+ };
40
+ const FAST_SESSION_REFRESH = {
41
+ minTurnsBetweenUpdate: 1,
42
+ minToolCallsBetweenUpdate: 1,
43
+ };
44
+ export function getSessionRefreshCadence(env = process.env) {
45
+ return env.PIPICLAW_TEST_FAST_MAINTENANCE === "1" ? FAST_SESSION_REFRESH : PRODUCTION_SESSION_REFRESH;
46
+ }
@@ -24,14 +24,13 @@ function renderLine(entry, now) {
24
24
  if (control) {
25
25
  parts.push(`priority ${control.priority}`);
26
26
  parts.push(`attempt ${control.usage.attempts}/${control.budget.maxAttempts}`);
27
- parts.push(`verify ${control.verification.mode}/${control.verification.status}`);
27
+ if (control.verification.required)
28
+ parts.push(`verify required/${control.verification.status}`);
28
29
  if (control.sideEffects !== "workspace") {
29
30
  parts.push(`effects ${control.sideEffects}/${control.externalApproval}`);
30
31
  }
31
32
  if (control.deadline)
32
33
  parts.push(`deadline ${control.deadline}`);
33
- if (control.dependsOn.length > 0)
34
- parts.push(`depends ${control.dependsOn.join(",")}`);
35
34
  if (control.nextAction)
36
35
  parts.push(`next ${control.nextAction}`);
37
36
  }
package/dist/paths.d.ts CHANGED
@@ -18,7 +18,6 @@ export declare const LOG_STATE_DIR: string;
18
18
  export declare const RUNTIME_LOG_PATH: string;
19
19
  export declare const USAGE_STATE_DIR: string;
20
20
  export declare const SUB_AGENTS_DIR_NAME = "sub-agents";
21
- export declare const SUB_AGENTS_DIR: string;
22
21
  export declare const CHANNEL_CONFIG_PATH: string;
23
22
  export declare const AUTH_CONFIG_PATH: string;
24
23
  export declare const MODELS_CONFIG_PATH: string;
package/dist/paths.js CHANGED
@@ -29,7 +29,6 @@ export const LOG_STATE_DIR = join(STATE_DIR, "logs");
29
29
  export const RUNTIME_LOG_PATH = join(LOG_STATE_DIR, "runtime.jsonl");
30
30
  export const USAGE_STATE_DIR = join(STATE_DIR, "usage");
31
31
  export const SUB_AGENTS_DIR_NAME = "sub-agents";
32
- export const SUB_AGENTS_DIR = join(WORKSPACE_DIR, SUB_AGENTS_DIR_NAME);
33
32
  export const CHANNEL_CONFIG_PATH = join(APP_HOME_DIR, "channel.json");
34
33
  export const AUTH_CONFIG_PATH = join(APP_HOME_DIR, "auth.json");
35
34
  export const MODELS_CONFIG_PATH = join(APP_HOME_DIR, "models.json");
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: task-delegation
3
- description: 拆分父子任务(task)、委派子代理(subagent),或创建任务隔离的 worktree 前。
3
+ description: 把工作拆成多个任务(task)、委派子代理(subagent),或交给外部 agent 工具之前。
4
4
  requires-tools: task_manage, subagent
5
5
  priority: 45
6
6
  ---
@@ -9,13 +9,9 @@ priority: 45
9
9
 
10
10
  只拆真正可分离、可独立验收的工作。两三步顺序操作留在一个 task,避免调度和 attempt 开销。
11
11
 
12
- ## 父子任务与依赖
12
+ ## 拆分任务
13
13
 
14
- - child 的 `control.parent` 指向父任务。
15
- - `dependsOn` 表示执行前置;依赖 done 前 driver 不运行 dependent。
16
- - 父任务可 dependsOn child,等待全部子成果汇合后集成。
17
- - 依赖缺失、cancelled 或被治理器暂停会令 dependent 被治理器暂停。
18
- - 父任务有未闭环 child 时不能 done。
14
+ 任务之间没有父子或依赖字段,每个任务独立按自己的 DoD 收尾。需要表达先后次序时,把它写进后继任务的 `goal`/`manual`("在 <前置任务> 完成后再开始"),或用 `wake` 把它排到前置任务预计完成之后。
19
15
 
20
16
  ## 配置 subagent
21
17
 
@@ -27,15 +23,13 @@ priority: 45
27
23
 
28
24
  ## 产物契约与回传预算
29
25
 
30
- 每次委派都会在 `channelDir/subagent-artifacts/<runId>/` 下建产物目录,子代理的完整输出总会落盘到该目录的 `output.md`,与 `returns` 无关。回传给父代理的文本超过大小预算时会被截断,附上 `output.md` 的绝对路径——父代理判断值得保留的内容,按需 `read` 全文,再决定是否经 `memory_manage` 提炼为记忆。产物目录不自动清理,和 worktree 一样由父代理负责闭环:任务收尾时决定保留还是删除。
26
+ 每次委派都会在 `channelDir/subagent-artifacts/<runId>/` 下建产物目录,子代理的完整输出总会落盘到该目录的 `output.md`,与 `returns` 无关。回传给父代理的文本超过大小预算时会被截断,附上 `output.md` 的绝对路径——父代理判断值得保留的内容,按需 `read` 全文,再决定是否经 `memory_manage` 提炼为记忆。产物目录不自动清理,由父代理负责闭环:任务收尾时决定保留还是删除。
31
27
 
32
28
  需要子代理把主产出写成文件而不是回传整段文本时传 `returns: "artifact"`,子代理需以 `ARTIFACT: <filename>` 结尾;忘记该标记时会自动降级为纯文本模式。
33
29
 
34
- ## worktree 隔离
30
+ ## 文件系统隔离
35
31
 
36
- 写密集 child 委派时传 `isolation: worktree` 和 taskId——隔离在委派点声明一次即可,任务本身不需要预先标注。runtime 从 committed HEAD 创建 `pipiclaw-task/<task>/<run>` 分支,把路径/分支记录进 task control。
37
-
38
- 同一 taskId 的后续委派自动复用台账里记录的 worktree,不需要也无法手工指定路径;台账记录的路径若已不在磁盘上则新建,若指向 `tasks/worktrees/` 之外则报错,需先用 `task_manage` 清理该元数据。worktree 不自动删除;父代理必须 review、merge、验证,然后清理 worktree 与分支。创建前处理好主 checkout 的未提交前置改动。
32
+ 没有。子代理与主代理共享同一个 checkout,只隔离对话上下文。需要在独立检出上作业时,在宿主侧自行 `git worktree add`,把它当作普通工作目录传给子代理,并自己负责 review、merge 与清理。
39
33
 
40
34
  ## 外部 agent 工具
41
35
 
@@ -49,4 +43,4 @@ runtime 只规定长程委派的恢复纪律:
49
43
  4. 如确需条件触发,按 `event-scheduling.md` 使用用户提供的稳定检测命令;不要临时复制未知脚本,也不要把第三方协议写进 runtime playbook。
50
44
  5. task 闭环前清理临时事件和外部实例。
51
45
 
52
- 任何委派都不能转移最终交付责任。父代理必须确认成果已进入目标 checkout,而不是只停留在孤儿 worktree、外部实例或口头报告中。
46
+ 任何委派都不能转移最终交付责任。父代理必须确认成果已进入目标 checkout,而不是只停留在外部实例或口头报告中。
@@ -50,7 +50,6 @@ priority: 41
50
50
 
51
51
  - 方向错:修 Manual/`nextAction`、重新拆解或 cancel。
52
52
  - 预算确实不足:向用户说明后用 `task_manage set` 调整 budget/deadline,并把 status 设回 `active`。
53
- - 依赖终止:恢复或重建依赖,或 `set` 更新 `dependsOn`。
54
53
 
55
54
  被暂停的任务不能 progress/candidate;`set`(或 `/tasks resume`)是审查原因后的修复入口,**不要反射性加预算**。
56
55
 
@@ -22,17 +22,15 @@ priority: 40
22
22
  - `manual`:可复用的执行步骤、预检与返工教训。
23
23
  - `verificationPlan`:验收者能独立执行的确定性检查。
24
24
 
25
- 默认独立验收(independent verification)加有限尝试预算。轻量记录性任务确实无需独立验收时,创建时设 `control.verificationMode: evidence`。
25
+ 默认不要求独立验收,只有有限尝试预算。任务产出了验收者能独立检查的产物(代码、配置、可运行命令)时,创建时设 `control.verificationRequired: true`;`sideEffects: external` 的任务会自动打开它。
26
26
 
27
27
  ## control 决策
28
28
 
29
29
  - `priority` / `deadline`:表达调度重要性和硬期限,不用 `wake` 冒充 deadline。
30
30
  - `nextAction`:下一条可执行动作,避免写抽象愿望。
31
- - `maxAttempts` / `maxTokens` / `maxCostUsd` / `maxWallTimeMinutes`:按风险和规模收紧;这些是**本周期、回合边界检查**的停止条件,不会中断正在运行的单个回合。模型没有价格元数据时不能使用 `maxCostUsd`,改用 `maxTokens`。
31
+ - `maxAttempts`:唯一的按任务停止条件,按风险和规模收紧。它在**本周期、回合边界**检查,不会中断正在运行的单个回合。
32
32
  - `sideEffects`:`workspace` 或 `external`。发送、发布、部署、修改外部系统必须选 `external`,它会要求用户 `/tasks approve` 后才能 done。
33
- - `parent` / `dependsOn`:只用于真实分解;`parent` 表归属,`dependsOn` 表执行前置。
34
-
35
- 创建和 `set` 会拒绝不存在的关联、自指、parent 环和 dependency 环。父任务可以 `dependsOn` 自己的 child 表达 join;父任务有未闭环 child 时不能 done。
33
+ - 任务之间没有父子或依赖字段。需要表达先后次序时写进 `goal`/`manual`,或用 `wake` 把后续任务排到合适的时间;每个任务只按自己的 DoD 收尾。
36
34
 
37
35
  外部副作用与独立验收并存时,DoD/Verification 要验收"**待执行动作及其输入已准备正确**"(内容、目标、参数、预演、回滚方案),不要把尚未获批的外部动作本身写成 candidate 前必须勾选的项——否则会形成"先执行才能勾选"与"先验收批准才能执行"的死循环。实际执行结果由审批记录和 done evidence 收口。
38
36
 
@@ -44,6 +44,20 @@ export interface RuntimeContext {
44
44
  nudge?(): void;
45
45
  runOnce?: (now?: Date) => Promise<void>;
46
46
  };
47
+ /**
48
+ * Production maintenance scheduler, exposed for the same reason as `taskDriver`.
49
+ *
50
+ * Evaluation workers run with `startServices: false`, so the background timer never fires and
51
+ * no trial could otherwise reach `SESSION.md` refresh, the memory checkpoint, or consolidation
52
+ * — the whole layered memory pipeline was structurally untestable from a behavior eval.
53
+ * Exposing the instance lets a case drive one real pass at a chosen time instead of faking a
54
+ * clock or re-implementing the job order.
55
+ */
56
+ memoryMaintenance: {
57
+ start(): void;
58
+ stop(): void;
59
+ runOnce?: (now?: Date) => Promise<void>;
60
+ };
47
61
  shutdown: (reason?: NodeJS.Signals | "manual") => Promise<void>;
48
62
  }
49
63
  export declare const DEFAULT_BOOTSTRAP_PATHS: BootstrapPaths;
@@ -837,6 +837,7 @@ export function createRuntimeContext(options) {
837
837
  store,
838
838
  bot,
839
839
  taskDriver,
840
+ memoryMaintenance: memoryMaintenanceScheduler,
840
841
  shutdown: shutdownWithReason,
841
842
  };
842
843
  }
@@ -857,6 +858,13 @@ export function prepareAppServices(paths = DEFAULT_BOOTSTRAP_PATHS) {
857
858
  for (const { scope, error } of settingsManager.drainErrors()) {
858
859
  log.logWarning(`Failed to load ${scope} settings`, `${error.message}\n${paths.settingsConfigPath}`);
859
860
  }
861
+ // Errors already went out above with a richer message; this pass exists for the
862
+ // warnings, chiefly retired settings keys (spec 035 D3).
863
+ for (const diagnostic of settingsManager.getDiagnostics()) {
864
+ if (diagnostic.severity === "error")
865
+ continue;
866
+ log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
867
+ }
860
868
  for (const diagnostic of loadToolsConfigWithDiagnostics(paths.appHomeDir).diagnostics) {
861
869
  log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
862
870
  }
@@ -4,7 +4,8 @@ import { join, resolve, sep } from "node:path";
4
4
  import { parseTaskEventName, taskEventPrefix } from "../shared/task-events.js";
5
5
  import { extractTaskTitle, missingStandardTaskSections, normalizeTaskId, readActiveTasks, } from "../shared/task-ledger.js";
6
6
  import { errorMessage } from "../shared/text-utils.js";
7
- import { taskBudgetViolation } from "../tasks/control.js";
7
+ import { isRecord } from "../shared/type-guards.js";
8
+ import { retiredTaskControlKeys, taskBudgetViolation } from "../tasks/control.js";
8
9
  import { claimTaskAttempt, readStoredTask, releaseTaskAttemptClaim, taskBodyHash, writeStoredTask, } from "../tasks/store.js";
9
10
  import { normalizeStoredStatus, resolveTaskTransition } from "../tasks/transitions.js";
10
11
  import { readVerificationAttestation } from "../tasks/verification.js";
@@ -144,34 +145,25 @@ function validWakeMs(entry) {
144
145
  function issue(problem, nextStep) {
145
146
  return `- ${problem}\n Next step: ${nextStep}`;
146
147
  }
147
- function relationCycles(graph) {
148
- const visited = new Set();
149
- const active = new Set();
150
- const stack = [];
151
- const cycles = new Map();
152
- const visit = (id) => {
153
- if (active.has(id)) {
154
- const start = stack.indexOf(id);
155
- const cycle = [...stack.slice(start), id];
156
- const key = [...new Set(cycle)].sort().join("\0");
157
- cycles.set(key, cycle);
158
- return;
148
+ /**
149
+ * Render the ordering edges a stored task still declares, e.g. `child → parent, a → b`.
150
+ * Empty when the task carries no retired relation keys (spec 036, D8).
151
+ */
152
+ function describeDroppedTaskRelations(id, rawControl) {
153
+ if (!isRecord(rawControl))
154
+ return "";
155
+ const edges = [];
156
+ const parent = rawControl.parent;
157
+ if (typeof parent === "string" && parent.trim())
158
+ edges.push(`${id} → ${parent.trim()}`);
159
+ const dependsOn = rawControl.dependsOn;
160
+ if (Array.isArray(dependsOn)) {
161
+ for (const dependency of dependsOn) {
162
+ if (typeof dependency === "string" && dependency.trim())
163
+ edges.push(`${id} → ${dependency.trim()}`);
159
164
  }
160
- if (visited.has(id))
161
- return;
162
- visited.add(id);
163
- active.add(id);
164
- stack.push(id);
165
- for (const next of graph.get(id) ?? []) {
166
- if (graph.has(next))
167
- visit(next);
168
- }
169
- stack.pop();
170
- active.delete(id);
171
- };
172
- for (const id of graph.keys())
173
- visit(id);
174
- return Array.from(cycles.values());
165
+ }
166
+ return edges.join(", ");
175
167
  }
176
168
  async function readActiveTaskContent(channelDir, id) {
177
169
  try {
@@ -195,20 +187,15 @@ async function listTasks(channelDir) {
195
187
  if (control) {
196
188
  detail.push(`priority: ${control.priority}`);
197
189
  detail.push(`attempts: ${control.usage.attempts}/${control.budget.maxAttempts}`);
198
- detail.push(`verify: ${control.verification.mode}/${control.verification.status}`);
190
+ if (control.verification.required)
191
+ detail.push(`verify: required/${control.verification.status}`);
199
192
  if (control.sideEffects !== "workspace") {
200
193
  detail.push(`effects: ${control.sideEffects}/${control.externalApproval}`);
201
194
  }
202
195
  if (control.deadline)
203
196
  detail.push(`deadline: ${control.deadline}`);
204
- if (control.parent)
205
- detail.push(`parent: ${control.parent}`);
206
- if (control.dependsOn.length > 0)
207
- detail.push(`depends: ${control.dependsOn.join(",")}`);
208
197
  if (control.nextAction)
209
198
  detail.push(`next: ${control.nextAction}`);
210
- if (control.worktree?.branch)
211
- detail.push(`branch: ${control.worktree.branch}`);
212
199
  if (control.cycleId) {
213
200
  detail.push(`${status === "done" ? "last" : "current"} cycle: ${control.cycleId}`);
214
201
  }
@@ -321,15 +308,11 @@ function renderUsageLine(entry) {
321
308
  return `- ${entry.id}: legacy task (no governed usage recorded)`;
322
309
  const verification = control.verification;
323
310
  const cycleCost = control.usage.costKnown ? `$${control.usage.costUsd.toFixed(4)}` : "unavailable";
324
- const lifetimeCost = control.lifetimeUsage.costKnown
325
- ? `$${control.lifetimeUsage.costUsd.toFixed(4)}`
326
- : "unavailable";
327
311
  return [
328
312
  `- ${entry.id} — ${entry.title}`,
329
313
  ` this cycle: ${control.usage.attempts}/${control.budget.maxAttempts} attempts, ${control.usage.tokens} tokens, ${cycleCost}, ${control.usage.wallTimeMinutes.toFixed(1)}m`,
330
- ` recorded lifetime: ${control.lifetimeUsage.attempts} attempts, ${control.lifetimeUsage.tokens} tokens, ${lifetimeCost}, ${control.lifetimeUsage.wallTimeMinutes.toFixed(1)}m`,
331
314
  ` last run: ${control.lastOutcome}`,
332
- ` verification: ${verification.mode}/${verification.status}`,
315
+ ` verification: ${verification.required ? "required" : "not required"}/${verification.status}`,
333
316
  ].join("\n");
334
317
  }
335
318
  async function taskStats(options, idInput) {
@@ -356,30 +339,13 @@ async function taskStats(options, idInput) {
356
339
  const governed = entries.filter((entry) => entry.frontmatter.control);
357
340
  const totals = governed.reduce((total, entry) => {
358
341
  const usage = entry.frontmatter.control.usage;
359
- const lifetime = entry.frontmatter.control.lifetimeUsage;
360
342
  total.attempts += usage.attempts;
361
343
  total.tokens += usage.tokens;
362
344
  total.costUsd += usage.costUsd;
363
345
  total.costKnown &&= usage.costKnown;
364
346
  total.wallTimeMinutes += usage.wallTimeMinutes;
365
- total.lifetimeAttempts += lifetime.attempts;
366
- total.lifetimeTokens += lifetime.tokens;
367
- total.lifetimeCostUsd += lifetime.costUsd;
368
- total.lifetimeCostKnown &&= lifetime.costKnown;
369
- total.lifetimeWallTimeMinutes += lifetime.wallTimeMinutes;
370
347
  return total;
371
- }, {
372
- attempts: 0,
373
- tokens: 0,
374
- costUsd: 0,
375
- costKnown: true,
376
- wallTimeMinutes: 0,
377
- lifetimeAttempts: 0,
378
- lifetimeTokens: 0,
379
- lifetimeCostUsd: 0,
380
- lifetimeCostKnown: true,
381
- lifetimeWallTimeMinutes: 0,
382
- });
348
+ }, { attempts: 0, tokens: 0, costUsd: 0, costKnown: true, wallTimeMinutes: 0 });
383
349
  const verified = governed.filter((entry) => entry.frontmatter.control?.verification.status === "passed").length;
384
350
  const stalled = governed.filter((entry) => entry.frontmatter.control?.lastOutcome === "failed").length;
385
351
  return [
@@ -387,7 +353,6 @@ async function taskStats(options, idInput) {
387
353
  "",
388
354
  `governed tasks: ${governed.length}/${entries.length}`,
389
355
  `this cycle: ${totals.attempts} attempts, ${totals.tokens} tokens, ${totals.costKnown ? `$${totals.costUsd.toFixed(4)}` : "cost unavailable"}, ${totals.wallTimeMinutes.toFixed(1)}m`,
390
- `recorded lifetime: ${totals.lifetimeAttempts} attempts, ${totals.lifetimeTokens} tokens, ${totals.lifetimeCostKnown ? `$${totals.lifetimeCostUsd.toFixed(4)}` : "cost unavailable"}, ${totals.lifetimeWallTimeMinutes.toFixed(1)}m`,
391
356
  `verification PASS: ${verified}`,
392
357
  `last-run failures: ${stalled}`,
393
358
  "",
@@ -456,11 +421,6 @@ async function doctor(options) {
456
421
  if (violation) {
457
422
  issues.push(issue(`tasks/${entry.id}.md exceeds its control limit: ${violation}.`, `Review the task, then explicitly raise its budget/deadline or cancel it; the driver will escalate it.`));
458
423
  }
459
- for (const relatedId of [control.parent, ...control.dependsOn].filter((value) => Boolean(value))) {
460
- if (!activeIds.has(relatedId) && !archivedIds.has(relatedId)) {
461
- issues.push(issue(`tasks/${entry.id}.md points to missing related task ${relatedId}.`, `Create ${relatedId}, or remove it from parent/dependsOn with task_manage set.`));
462
- }
463
- }
464
424
  if (control.sideEffects === "external" && control.externalApproval === "required") {
465
425
  issues.push(issue(`tasks/${entry.id}.md requires external side effects but has no user approval.`, `After reviewing the proposed action, a user must run /tasks approve ${entry.id}.`));
466
426
  }
@@ -469,14 +429,11 @@ async function doctor(options) {
469
429
  control.approvalBodyHash !== taskBodyHash(storedTask.body)) {
470
430
  issues.push(issue(`tasks/${entry.id}.md changed after external-action approval was granted.`, `Review the current action and run /tasks approve ${entry.id} again.`));
471
431
  }
472
- if (control.worktree && !existsSync(control.worktree.path)) {
473
- issues.push(issue(`tasks/${entry.id}.md records a missing worktree path: ${control.worktree.path}.`, `Clear the stale worktree metadata or create/reassign an isolated worktree.`));
474
- }
475
432
  if (status !== "done" && control.verification.status === "passed" && control.verification.bodyHash) {
476
433
  if (storedTask && taskBodyHash(storedTask.body) !== control.verification.bodyHash) {
477
434
  issues.push(issue(`tasks/${entry.id}.md changed after its recorded independent PASS.`, `Run a fresh purpose=verify sub-agent and import its attestation before completion.`));
478
435
  }
479
- else if (control.verification.mode === "independent") {
436
+ else if (control.verification.required) {
480
437
  const attestationOk = control.verification.runId
481
438
  ? await readVerificationAttestation(options.channelDir, control.verification.runId)
482
439
  .then((attestation) => attestation.taskId === entry.id && attestation.verdict === "pass")
@@ -506,20 +463,17 @@ async function doctor(options) {
506
463
  issues.push(issue(`tasks/${entry.id}.md has an invalid wake value (${entry.frontmatter.wake}); the native driver will treat it as due.`, `Use task_manage set or progress to replace wake with ISO8601, or clear it if the task should continue now.`));
507
464
  }
508
465
  }
509
- const parentGraph = new Map();
510
- const dependencyGraph = new Map();
466
+ // Spec 036 D8: retired control keys are ignored on read, which keeps stored tasks readable
467
+ // but silently discards whatever `parent`/`dependsOn` once expressed. Report the loss —
468
+ // naming the dropped edges, not just the key — so the user can restate any real ordering.
511
469
  for (const entry of entries) {
512
- const control = entry.frontmatter.control;
513
- if (!control)
470
+ const retired = retiredTaskControlKeys(entry.frontmatter.rawControl);
471
+ if (retired.length === 0)
514
472
  continue;
515
- parentGraph.set(entry.id, control.parent ? [control.parent] : []);
516
- dependencyGraph.set(entry.id, control.dependsOn);
517
- }
518
- for (const cycle of relationCycles(parentGraph)) {
519
- issues.push(issue(`Task parent cycle detected: ${cycle.join(" → ")}.`, `Use task_manage set to clear or correct one parent link in this cycle.`));
520
- }
521
- for (const cycle of relationCycles(dependencyGraph)) {
522
- issues.push(issue(`Task dependency cycle detected: ${cycle.join(" → ")}.`, `Use task_manage set to remove one dependsOn edge before the driver can continue these tasks.`));
473
+ const edges = describeDroppedTaskRelations(entry.id, entry.frontmatter.rawControl);
474
+ issues.push(issue(`tasks/${entry.id}.md still carries retired control keys: ${retired.join(", ")}.${edges ? ` Dropped ordering: ${edges}.` : ""}`, edges
475
+ ? `These no longer constrain execution. Restate any real ordering in the task body or with wake, then remove the keys (any task_manage write drops them).`
476
+ : `They are ignored; any task_manage write drops them.`));
523
477
  }
524
478
  for (const event of events) {
525
479
  if (!event.id || !event.use) {