@oyasmi/pipiclaw 0.8.10-beta.2 → 0.8.10-beta.4

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 (60) hide show
  1. package/dist/agent/channel-runner.d.ts +12 -0
  2. package/dist/agent/channel-runner.js +54 -15
  3. package/dist/agent/commands.js +30 -28
  4. package/dist/agent/effect-ledger.d.ts +25 -4
  5. package/dist/agent/effect-ledger.js +45 -5
  6. package/dist/agent/job-manager.d.ts +20 -0
  7. package/dist/agent/job-manager.js +66 -10
  8. package/dist/agent/maintenance-context.js +3 -2
  9. package/dist/agent/progress-formatter.d.ts +10 -1
  10. package/dist/agent/progress-formatter.js +14 -2
  11. package/dist/agent/prompt/manifest.d.ts +32 -1
  12. package/dist/agent/prompt/manifest.js +41 -2
  13. package/dist/executor.d.ts +2 -0
  14. package/dist/executor.js +1 -0
  15. package/dist/memory/maintenance-gates.d.ts +24 -10
  16. package/dist/memory/maintenance-gates.js +11 -9
  17. package/dist/memory/maintenance-jobs.d.ts +3 -2
  18. package/dist/memory/maintenance-jobs.js +33 -21
  19. package/dist/memory/scheduler.d.ts +7 -2
  20. package/dist/playbooks/task-closeout.md +2 -0
  21. package/dist/playbooks/task-delegation.md +14 -8
  22. package/dist/playbooks/task-driving.md +8 -5
  23. package/dist/playbooks/task-planning.md +2 -2
  24. package/dist/runtime/bootstrap.js +35 -9
  25. package/dist/runtime/delivery.d.ts +12 -2
  26. package/dist/runtime/delivery.js +55 -13
  27. package/dist/runtime/dingtalk.d.ts +9 -1
  28. package/dist/runtime/dingtalk.js +7 -4
  29. package/dist/runtime/task-commands.js +170 -54
  30. package/dist/runtime/task-driver.d.ts +3 -3
  31. package/dist/runtime/task-driver.js +42 -12
  32. package/dist/settings.d.ts +10 -0
  33. package/dist/settings.js +14 -0
  34. package/dist/shared/file-stamp.d.ts +10 -0
  35. package/dist/shared/file-stamp.js +19 -0
  36. package/dist/shared/task-ledger.d.ts +12 -1
  37. package/dist/shared/task-ledger.js +34 -3
  38. package/dist/subagents/tool.d.ts +1 -0
  39. package/dist/subagents/tool.js +33 -3
  40. package/dist/tasks/control.d.ts +1 -0
  41. package/dist/tasks/control.js +2 -2
  42. package/dist/tasks/transitions.d.ts +2 -1
  43. package/dist/tasks/transitions.js +2 -1
  44. package/dist/tasks/verification.d.ts +8 -0
  45. package/dist/tasks/verification.js +4 -1
  46. package/dist/tools/bash.js +12 -12
  47. package/dist/tools/task-manage/lifecycle.js +9 -6
  48. package/dist/tools/task-manage/schema.d.ts +1 -3
  49. package/dist/tools/task-manage/schema.js +6 -5
  50. package/dist/tools/task-manage/shared.d.ts +8 -0
  51. package/dist/tools/task-manage/shared.js +17 -1
  52. package/dist/tools/task-manage/types.d.ts +20 -21
  53. package/dist/tools/task-manage/verification.d.ts +2 -1
  54. package/dist/tools/task-manage/verification.js +2 -1
  55. package/dist/tools/task-manage.js +4 -20
  56. package/dist/tui/turn-controller.js +3 -3
  57. package/dist/usage/ledger.d.ts +2 -0
  58. package/dist/usage/ledger.js +7 -2
  59. package/dist/usage/render.js +17 -8
  60. package/package.json +1 -1
@@ -4,14 +4,26 @@ function sanitizeProgressText(text) {
4
4
  .replace(/\r/g, "")
5
5
  .trim();
6
6
  }
7
- export function clipUserInput(text, maxChars) {
7
+ /**
8
+ * Head + tail of an over-length message, with the middle replaced by a marker.
9
+ *
10
+ * `fullTextPath` matters more than it looks: the dropped middle of a pasted build log is exactly
11
+ * where the failing stack trace lives, so a marker that only says "omitted" hands the model a
12
+ * mutilated input and no way to notice. When the caller managed to persist the original, the
13
+ * marker names it and says how to read it (the same next-step rule every other truncated output
14
+ * in this runtime follows).
15
+ */
16
+ export function clipUserInput(text, maxChars, fullTextPath) {
8
17
  const normalized = text.replace(/\r/g, "").trim();
9
18
  if (normalized.length <= maxChars) {
10
19
  return normalized;
11
20
  }
12
21
  const headChars = Math.floor(maxChars * 0.6);
13
22
  const tailChars = maxChars - headChars;
14
- return `${normalized.slice(0, headChars)}\n\n[... omitted ${normalized.length - maxChars} chars ...]\n\n${normalized.slice(-tailChars)}`;
23
+ const recovery = fullTextPath
24
+ ? `; the complete message is saved at ${fullTextPath} — page through it with the read tool before drawing conclusions about the omitted part`
25
+ : "";
26
+ return `${normalized.slice(0, headChars)}\n\n[... omitted ${normalized.length - maxChars} chars${recovery} ...]\n\n${normalized.slice(-tailChars)}`;
15
27
  }
16
28
  export function formatProgressEntry(kind, text) {
17
29
  const cleaned = sanitizeProgressText(text);
@@ -12,6 +12,37 @@
12
12
  import type { LoadedPromptResource, PromptBuildResult } from "./types.js";
13
13
  /** The design ceiling for everything Pipiclaw auto-appends to a turn (spec 026 §5.3). */
14
14
  export declare const AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS = 3000;
15
+ /**
16
+ * Soft budget for the tool JSON schemas, in the same units as the prompt sections.
17
+ *
18
+ * Tool schemas are the larger half of the fixed per-turn cost and were the only part of it with
19
+ * no budget at all: the runtime-authored prompt is capped at 700 units while the schemas beside it
20
+ * run several thousand. They sit in the provider's cache prefix, so the steady-state price is low —
21
+ * but every `rebuildSessionTools` (a `skill_manage` write, `/reload`, any resource reload) swaps
22
+ * that prefix and pays for all of it again.
23
+ *
24
+ * There is no hard cap on purpose. A schema cannot be auto-trimmed the way a prompt section can:
25
+ * the fix is always a human deciding which tool says less, or which tool should not be registered.
26
+ * So this is a warning line in the log and in `/context`, not an enforcement point. It is set just
27
+ * above the current set (≈2.8k units for 15 tools) — one more heavyweight tool crosses it, which
28
+ * is exactly when someone should be looking.
29
+ */
30
+ export declare const TOOL_SCHEMA_TARGET_UNITS = 3000;
31
+ export interface ToolSchemaMeasurement {
32
+ chars: number;
33
+ units: number;
34
+ }
35
+ /** The one wording for "the tool set is over budget", shared by `/context` and the rebuild log. */
36
+ export declare function toolSchemaBudgetWarning(measurement: ToolSchemaMeasurement): string;
37
+ /**
38
+ * What the tool set costs on top of the system prompt. Counts what the provider is actually sent
39
+ * per tool — name, description and the JSON schema — the same way `/context` has always reported it.
40
+ */
41
+ export declare function measureToolSchemas(tools: Array<{
42
+ name: string;
43
+ description: string;
44
+ parameters?: unknown;
45
+ }>): ToolSchemaMeasurement;
15
46
  export interface PromptTurnContextStats {
16
47
  durableMemoryChars: number;
17
48
  durableMemoryUnits: number;
@@ -31,7 +62,7 @@ export interface PromptContextReportInput {
31
62
  description: string;
32
63
  }>;
33
64
  toolNames: string[];
34
- toolSchemaChars: number;
65
+ toolSchemas: ToolSchemaMeasurement;
35
66
  /** Resolved SOUL.md / AGENTS.md, for the independent body-budget lines. */
36
67
  soul?: LoadedPromptResource;
37
68
  agents?: LoadedPromptResource;
@@ -9,9 +9,44 @@
9
9
  * owns the same list that backs `/skill:name`, so `estimateSkillsPromptChars` lives
10
10
  * next to the report — not in the builder's budget path (spec 026 §9, §10.9).
11
11
  */
12
+ import { countPromptUnits } from "../../shared/prompt-units.js";
12
13
  import { estimateTokens, RUNTIME_PROMPT_TARGET_UNITS, sha256 } from "./builder.js";
13
14
  /** The design ceiling for everything Pipiclaw auto-appends to a turn (spec 026 §5.3). */
14
15
  export const AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS = 3_000;
16
+ /**
17
+ * Soft budget for the tool JSON schemas, in the same units as the prompt sections.
18
+ *
19
+ * Tool schemas are the larger half of the fixed per-turn cost and were the only part of it with
20
+ * no budget at all: the runtime-authored prompt is capped at 700 units while the schemas beside it
21
+ * run several thousand. They sit in the provider's cache prefix, so the steady-state price is low —
22
+ * but every `rebuildSessionTools` (a `skill_manage` write, `/reload`, any resource reload) swaps
23
+ * that prefix and pays for all of it again.
24
+ *
25
+ * There is no hard cap on purpose. A schema cannot be auto-trimmed the way a prompt section can:
26
+ * the fix is always a human deciding which tool says less, or which tool should not be registered.
27
+ * So this is a warning line in the log and in `/context`, not an enforcement point. It is set just
28
+ * above the current set (≈2.8k units for 15 tools) — one more heavyweight tool crosses it, which
29
+ * is exactly when someone should be looking.
30
+ */
31
+ export const TOOL_SCHEMA_TARGET_UNITS = 3_000;
32
+ /** The one wording for "the tool set is over budget", shared by `/context` and the rebuild log. */
33
+ export function toolSchemaBudgetWarning(measurement) {
34
+ return `tool JSON schemas are ${measurement.units} units (${measurement.chars} chars), over the ${TOOL_SCHEMA_TARGET_UNITS} unit target. Shorten a tool description, move detail into a playbook, or unregister a tool; \`/context detail\` lists the set.`;
35
+ }
36
+ /**
37
+ * What the tool set costs on top of the system prompt. Counts what the provider is actually sent
38
+ * per tool — name, description and the JSON schema — the same way `/context` has always reported it.
39
+ */
40
+ export function measureToolSchemas(tools) {
41
+ let chars = 0;
42
+ let units = 0;
43
+ for (const tool of tools) {
44
+ const text = `${tool.name}${tool.description}${JSON.stringify(tool.parameters ?? {})}`;
45
+ chars += text.length;
46
+ units += countPromptUnits(text);
47
+ }
48
+ return { chars, units };
49
+ }
15
50
  /**
16
51
  * What pi's `<available_skills>` block will cost, close enough to report on:
17
52
  * name, description and location inside a five-line XML wrapper, plus the preamble.
@@ -82,7 +117,8 @@ export function renderContextReport(input) {
82
117
  lines.push(agentsLine);
83
118
  }
84
119
  lines.push("");
85
- lines.push(`Tools: ${input.toolNames.length} registered; JSON schemas ≈ ${formatNumber(input.toolSchemaChars)} chars (billed on top of the system prompt)`);
120
+ const overToolBudget = input.toolSchemas.units > TOOL_SCHEMA_TARGET_UNITS;
121
+ lines.push(`Tools: ${input.toolNames.length} registered; JSON schemas ≈ ${formatNumber(input.toolSchemas.units)} / ${formatNumber(TOOL_SCHEMA_TARGET_UNITS)} units, ${formatNumber(input.toolSchemas.chars)} chars${overToolBudget ? " — over target" : ""} (billed on top of the system prompt)`);
86
122
  lines.push(`Skills: ${input.skills.length} visible, ≈${formatNumber(estimateSkillsPromptChars(input.skills))} chars (rendered and managed by pi, not budgeted by Pipiclaw)`);
87
123
  if (input.lastTurn) {
88
124
  const turn = input.lastTurn;
@@ -95,12 +131,15 @@ export function renderContextReport(input) {
95
131
  lines.push(`- durable bootstrap: ${formatNumber(turn.durableMemoryUnits)} units / ${formatNumber(turn.durableMemoryChars)} chars`);
96
132
  lines.push(`- user message: ${formatNumber(turn.userMessageChars)} chars (not automatic; not capped here)`);
97
133
  }
98
- if (build.diagnostics.length > 0) {
134
+ if (build.diagnostics.length > 0 || overToolBudget) {
99
135
  lines.push("");
100
136
  lines.push("Diagnostics:");
101
137
  for (const diagnostic of build.diagnostics) {
102
138
  lines.push(`- [${diagnostic.level}] ${diagnostic.sectionId}: ${diagnostic.message}`);
103
139
  }
140
+ if (overToolBudget) {
141
+ lines.push(`- [warning] tools: ${toolSchemaBudgetWarning(input.toolSchemas)}`);
142
+ }
104
143
  }
105
144
  if (detail) {
106
145
  lines.push("");
@@ -12,6 +12,8 @@ export interface ExecOptions {
12
12
  timeout?: number;
13
13
  signal?: AbortSignal;
14
14
  stdin?: string;
15
+ /** Directory to run the command in. Defaults to the daemon's own working directory. */
16
+ cwd?: string;
15
17
  }
16
18
  export interface ExecResult {
17
19
  stdout: string;
package/dist/executor.js CHANGED
@@ -13,6 +13,7 @@ class HostExecutor {
13
13
  return spawn("sh", ["-c", command], {
14
14
  detached: true,
15
15
  stdio: ["pipe", "pipe", "pipe"],
16
+ ...(options?.cwd ? { cwd: options.cwd } : {}),
16
17
  });
17
18
  }
18
19
  catch (err) {
@@ -6,39 +6,53 @@ export interface MaintenanceGateDecision {
6
6
  skipReason?: string;
7
7
  jobKind: MaintenanceJobKind;
8
8
  }
9
+ /**
10
+ * Material checks are passed as thunks, never as values.
11
+ *
12
+ * Every gate below decides on cheap state (settings, timestamps, idle/backoff windows) before it
13
+ * looks at any material, and the material is expensive to produce: scanning the whole transcript,
14
+ * building the incremental source window, reading MEMORY.md/HISTORY.md. Evaluating it up front is
15
+ * what made an idle daemon pay a real cost on every one-minute tick just to be denied.
16
+ */
9
17
  export interface SessionRefreshGateInput {
10
18
  now: Date;
11
19
  state: MemoryMaintenanceState;
12
20
  sessionMemory: PipiclawSessionMemorySettings;
13
21
  maintenance: PipiclawMemoryMaintenanceSettings;
14
22
  channelActive: boolean;
15
- hasNewSessionEntry: boolean;
16
- hasMeaningfulMaterial: boolean;
23
+ hasNewSessionEntry: () => boolean;
24
+ hasMeaningfulMaterial: () => boolean;
17
25
  }
18
- export interface MemoryCheckpointGateInput {
19
- now: Date;
20
- state: MemoryMaintenanceState;
21
- maintenance: PipiclawMemoryMaintenanceSettings;
22
- channelActive: boolean;
26
+ export interface MemoryCheckpointMaterial {
23
27
  hasNewEntry: boolean;
24
28
  hasMeaningfulExchange: boolean;
25
29
  batchSize: number;
26
- minBatchSize?: number;
27
30
  }
28
- export interface StructuralMaintenanceGateInput {
31
+ export interface MemoryCheckpointGateInput {
29
32
  now: Date;
30
33
  state: MemoryMaintenanceState;
31
34
  maintenance: PipiclawMemoryMaintenanceSettings;
32
35
  channelActive: boolean;
36
+ material: () => MemoryCheckpointMaterial;
37
+ minBatchSize?: number;
38
+ }
39
+ export interface StructuralMaintenanceMaterial {
33
40
  memoryCleanupNeeded: boolean;
34
41
  historyFoldingNeeded: boolean;
35
42
  hasMemoryContent: boolean;
36
43
  hasHistoryContent: boolean;
37
44
  }
45
+ export interface StructuralMaintenanceGateInput {
46
+ now: Date;
47
+ state: MemoryMaintenanceState;
48
+ maintenance: PipiclawMemoryMaintenanceSettings;
49
+ channelActive: boolean;
50
+ material: () => Promise<StructuralMaintenanceMaterial>;
51
+ }
38
52
  export interface StructuralMaintenanceGateDecision extends MaintenanceGateDecision {
39
53
  runMemoryCleanup: boolean;
40
54
  runHistoryFolding: boolean;
41
55
  }
42
56
  export declare function shouldRunSessionRefresh(input: SessionRefreshGateInput): MaintenanceGateDecision;
43
57
  export declare function shouldRunMemoryCheckpoint(input: MemoryCheckpointGateInput): MaintenanceGateDecision;
44
- export declare function shouldRunStructuralMaintenance(input: StructuralMaintenanceGateInput): StructuralMaintenanceGateDecision;
58
+ export declare function shouldRunStructuralMaintenance(input: StructuralMaintenanceGateInput): Promise<StructuralMaintenanceGateDecision>;
@@ -51,10 +51,10 @@ export function shouldRunSessionRefresh(input) {
51
51
  if (!sessionRefreshThresholdMet(input.state, input.sessionMemory)) {
52
52
  return deny("session-refresh", "threshold-not-met");
53
53
  }
54
- if (!input.hasNewSessionEntry) {
54
+ if (!input.hasNewSessionEntry()) {
55
55
  return deny("session-refresh", "no-new-session-entry");
56
56
  }
57
- if (!input.hasMeaningfulMaterial) {
57
+ if (!input.hasMeaningfulMaterial()) {
58
58
  return deny("session-refresh", "no-meaningful-material");
59
59
  }
60
60
  return allow("session-refresh");
@@ -75,18 +75,19 @@ export function shouldRunMemoryCheckpoint(input) {
75
75
  if (isBeforeOptional(input.now, input.state.failureBackoffUntil)) {
76
76
  return deny("memory-checkpoint", "backoff-active");
77
77
  }
78
- if (!input.hasNewEntry) {
78
+ const material = input.material();
79
+ if (!material.hasNewEntry) {
79
80
  return deny("memory-checkpoint", "no-new-entry");
80
81
  }
81
- if (!input.hasMeaningfulExchange) {
82
+ if (!material.hasMeaningfulExchange) {
82
83
  return deny("memory-checkpoint", "no-meaningful-exchange");
83
84
  }
84
- if (input.batchSize < (input.minBatchSize ?? 2)) {
85
+ if (material.batchSize < (input.minBatchSize ?? 2)) {
85
86
  return deny("memory-checkpoint", "batch-threshold-not-met");
86
87
  }
87
88
  return allow("memory-checkpoint");
88
89
  }
89
- export function shouldRunStructuralMaintenance(input) {
90
+ export async function shouldRunStructuralMaintenance(input) {
90
91
  const jobKind = "structural-maintenance";
91
92
  const denyStructural = (skipReason) => ({
92
93
  allowed: false,
@@ -104,11 +105,12 @@ export function shouldRunStructuralMaintenance(input) {
104
105
  if (isBeforeOptional(input.now, input.state.failureBackoffUntil)) {
105
106
  return denyStructural("backoff-active");
106
107
  }
107
- if (!input.hasMemoryContent && !input.hasHistoryContent) {
108
+ const material = await input.material();
109
+ if (!material.hasMemoryContent && !material.hasHistoryContent) {
108
110
  return denyStructural("empty-template-files");
109
111
  }
110
- const runMemoryCleanup = input.memoryCleanupNeeded;
111
- const runHistoryFolding = input.historyFoldingNeeded;
112
+ const runMemoryCleanup = material.memoryCleanupNeeded;
113
+ const runHistoryFolding = material.historyFoldingNeeded;
112
114
  if (!runMemoryCleanup && !runHistoryFolding) {
113
115
  return denyStructural("nothing-to-maintain");
114
116
  }
@@ -17,8 +17,9 @@ interface BaseMaintenanceJobInput {
17
17
  settings: MaintenanceJobSettings;
18
18
  model: Model<Api>;
19
19
  resolveApiKey: (model: Model<Api>) => Promise<string>;
20
- messages: AgentMessage[];
21
- sessionEntries: SessionEntry[];
20
+ /** Transcript accessors: only called once a gate has decided the job may actually run. */
21
+ messages: () => AgentMessage[];
22
+ sessionEntries: () => SessionEntry[];
22
23
  queue?: ChannelMemoryQueue;
23
24
  }
24
25
  export interface SessionRefreshJobInput extends BaseMaintenanceJobInput {
@@ -8,6 +8,14 @@ import { appendMemoryReviewLog } from "./review-log.js";
8
8
  import { updateChannelSessionMemory } from "./session.js";
9
9
  import { buildIncrementalMemorySourceWindow } from "./source-window.js";
10
10
  import { sanitizeMessagesForMemory } from "./transcript.js";
11
+ /** Evaluate `load` at most once, so a gate and the job body can share one expensive read. */
12
+ function once(load) {
13
+ let cached;
14
+ return () => {
15
+ cached ??= { value: load() };
16
+ return cached.value;
17
+ };
18
+ }
11
19
  function latestEntryId(entries) {
12
20
  return entries.at(-1)?.id;
13
21
  }
@@ -52,8 +60,8 @@ function makeRunOptions(input, usageCorrelationId) {
52
60
  channelDir: input.channelDir,
53
61
  model: input.model,
54
62
  resolveApiKey: input.resolveApiKey,
55
- messages: input.messages,
56
- sessionEntries: input.sessionEntries,
63
+ messages: input.messages(),
64
+ sessionEntries: input.sessionEntries(),
57
65
  usageCorrelationId,
58
66
  minAutoWriteConfidence: input.settings.memoryMaintenance.minMemoryAutoWriteConfidence,
59
67
  };
@@ -90,26 +98,28 @@ export async function runSessionRefreshJob(input) {
90
98
  return runQueued(input, async () => {
91
99
  const now = input.now ?? new Date();
92
100
  const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
93
- const latestId = latestEntryId(input.sessionEntries);
101
+ const messages = once(input.messages);
102
+ const latestEntry = once(() => latestEntryId(input.sessionEntries()));
94
103
  const decision = shouldRunSessionRefresh({
95
104
  now,
96
105
  state,
97
106
  sessionMemory: input.settings.sessionMemory,
98
107
  maintenance: input.settings.memoryMaintenance,
99
108
  channelActive: input.channelActive,
100
- hasNewSessionEntry: latestId !== undefined && latestId !== state.lastSessionRefreshedEntryId,
101
- hasMeaningfulMaterial: hasMeaningfulMessages(input.messages),
109
+ hasNewSessionEntry: () => latestEntry() !== undefined && latestEntry() !== state.lastSessionRefreshedEntryId,
110
+ hasMeaningfulMaterial: () => hasMeaningfulMessages(messages()),
102
111
  });
103
112
  if (!decision.allowed) {
104
113
  await appendJobReviewLog(input.channelDir, input.channelId, "session-refresh-job", { skipped: [{ target: "SESSION.md", reason: decision.skipReason }] }, now);
105
114
  return skipped(decision.jobKind, decision.skipReason ?? "skipped");
106
115
  }
116
+ const latestId = latestEntry();
107
117
  try {
108
118
  const correlationId = `session-refresh:${latestId ?? now.toISOString()}`;
109
119
  await updateChannelSessionMemory({
110
120
  channelId: input.channelId,
111
121
  channelDir: input.channelDir,
112
- messages: input.messages,
122
+ messages: messages(),
113
123
  model: input.model,
114
124
  resolveApiKey: input.resolveApiKey,
115
125
  timeoutMs: input.settings.sessionMemory.timeoutMs,
@@ -142,26 +152,31 @@ export async function runMemoryCheckpointJob(input) {
142
152
  return runQueued(input, async () => {
143
153
  const now = input.now ?? new Date();
144
154
  const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
145
- const sourceWindow = buildIncrementalMemorySourceWindow({
146
- entries: input.sessionEntries,
155
+ const loadSourceWindow = once(() => buildIncrementalMemorySourceWindow({
156
+ entries: input.sessionEntries(),
147
157
  lastEntryId: state.lastCheckpointEntryId,
148
158
  sourceKind: "idle",
149
- fallbackMessages: input.messages,
150
- });
151
- const newEntries = sourceWindow.entries;
159
+ fallbackMessages: input.messages(),
160
+ }));
152
161
  const decision = shouldRunMemoryCheckpoint({
153
162
  now,
154
163
  state,
155
164
  maintenance: input.settings.memoryMaintenance,
156
165
  channelActive: input.channelActive,
157
- hasNewEntry: newEntries.length > 0,
158
- hasMeaningfulExchange: hasMeaningfulMessages(sourceWindow.messages),
159
- batchSize: newEntries.length,
166
+ material: () => {
167
+ const window = loadSourceWindow();
168
+ return {
169
+ hasNewEntry: window.entries.length > 0,
170
+ hasMeaningfulExchange: hasMeaningfulMessages(window.messages),
171
+ batchSize: window.entries.length,
172
+ };
173
+ },
160
174
  });
161
175
  if (!decision.allowed) {
162
176
  await appendJobReviewLog(input.channelDir, input.channelId, "memory-checkpoint-job", { skipped: [{ target: "consolidation", reason: decision.skipReason }] }, now);
163
177
  return skipped(decision.jobKind, decision.skipReason ?? "skipped");
164
178
  }
179
+ const sourceWindow = loadSourceWindow();
165
180
  try {
166
181
  const result = await runInlineConsolidation({
167
182
  ...makeRunOptions(input),
@@ -205,22 +220,19 @@ export async function runStructuralMaintenanceJob(input) {
205
220
  return runQueued(input, async () => {
206
221
  const now = input.now ?? new Date();
207
222
  const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
208
- const [currentMemory, currentHistory] = await Promise.all([
209
- readChannelMemory(input.channelDir),
210
- readChannelHistory(input.channelDir),
211
- ]);
212
- const stats = getStructuralMaintenanceStats(currentMemory, currentHistory);
213
- const decision = shouldRunStructuralMaintenance({
223
+ const loadFiles = once(() => Promise.all([readChannelMemory(input.channelDir), readChannelHistory(input.channelDir)]));
224
+ const decision = await shouldRunStructuralMaintenance({
214
225
  now,
215
226
  state,
216
227
  maintenance: input.settings.memoryMaintenance,
217
228
  channelActive: input.channelActive,
218
- ...stats,
229
+ material: async () => getStructuralMaintenanceStats(...(await loadFiles())),
219
230
  });
220
231
  if (!decision.allowed) {
221
232
  await appendJobReviewLog(input.channelDir, input.channelId, "structural-maintenance-job", { skipped: [{ target: "structural-maintenance", reason: decision.skipReason }] }, now);
222
233
  return skipped(decision.jobKind, decision.skipReason ?? "skipped");
223
234
  }
235
+ const [currentMemory, currentHistory] = await loadFiles();
224
236
  try {
225
237
  const correlationId = `structural-maintenance:${now.toISOString()}`;
226
238
  const options = makeRunOptions(input, correlationId);
@@ -5,8 +5,13 @@ import type { PipiclawMemoryMaintenanceSettings, PipiclawSessionMemorySettings }
5
5
  export interface MemoryMaintenanceRuntimeContext {
6
6
  channelId: string;
7
7
  channelDir: string;
8
- messages: AgentMessage[];
9
- sessionEntries: SessionEntry[];
8
+ /**
9
+ * Transcript accessors, not arrays: the scheduler visits a channel every tick but almost
10
+ * every tick is denied by a cheap schedule gate. Copying (and then scanning) the whole
11
+ * transcript before that verdict was the entire steady-state cost of an idle daemon.
12
+ */
13
+ messages: () => AgentMessage[];
14
+ sessionEntries: () => SessionEntry[];
10
15
  model: Model<Api>;
11
16
  resolveApiKey: (model: Model<Api>) => Promise<string>;
12
17
  settings: {
@@ -7,6 +7,8 @@ priority: 42
7
7
 
8
8
  # 验收、外部审批与闭环
9
9
 
10
+ 本文件是验收(verify)与外部审批(approval)门禁规则的唯一真相源,`task-driving.md` 与 `task-planning.md` 只保留指针。
11
+
10
12
  ## 独立验收
11
13
 
12
14
  1. 只在证据成立后勾选 DoD / Verification checkbox。
@@ -29,18 +29,24 @@ priority: 45
29
29
 
30
30
  ## 文件系统隔离
31
31
 
32
- 没有。子代理与主代理共享同一个 checkout,只隔离对话上下文。需要在独立检出上作业时,在宿主侧自行 `git worktree add`,把它当作普通工作目录传给子代理,并自己负责 review、merge 与清理。
32
+ 没有。子代理默认与主代理共享同一个 checkout,只隔离对话上下文。需要在独立检出上作业时,在宿主侧自行 `git worktree add`,把该路径作为 `workingDirectory` 传给子代理(它是子代理的 shell cwd 与相对路径根,必须已存在),并自己负责 review、merge 与清理。`purpose: verify` 的 attestation 会绑定该目录的 git 产物状态,后续 `task_manage verify` / `done` 也在同一目录复算。
33
33
 
34
34
  ## 外部 agent 工具
35
35
 
36
- Pipiclaw 不内置或假设第三方 agent 工具的命令、状态 JSON、检测脚本。如何启动、inspect、capture、steer 由用户安装的可执行文件和 workspace skill 决定。
36
+ Pipiclaw 不内置或假设第三方 agent 工具的命令、状态 JSON、检测脚本。如何启动、探活、取回、steer 由用户安装的可执行文件和 workspace skill 决定——先读那份 skill,再决定用哪条命令,不要临时复制来源不明的脚本。
37
37
 
38
- runtime 只规定长程委派的恢复纪律:
38
+ 启动、纠偏、取回、停止都是秒级的同步命令,直接 `bash` 调用即可。runtime 只补它们补不了的那一块:**你不在场的那段等待**。按用户工具的能力从优到劣选一条:
39
39
 
40
- 1. 在 task 正文记录工具、实例标识、工作目录/分支、预期产物和验收方法。
41
- 2. `progress` 置 blocked,并设置合理 wake。
42
- 3. wake 后按用户 skill 检查状态;未完成则更新证据和 wake,完成则取回、review、验证并推进。
43
- 4. 如确需条件触发,按 `event-scheduling.md` 使用用户提供的稳定检测命令;不要临时复制未知脚本,也不要把第三方协议写进 runtime playbook。
44
- 5. task 闭环前清理临时事件和外部实例。
40
+ 1. **阻塞等待包成后台作业(首选)**:工具若提供"等到外部实例结束/空闲才返回"的命令,用 `bash async` + `taskId` 跑它,`progress` 置 `waiting` 且**不设 wake**,然后结束回合——作业结束时 runtime 自动叫醒你并带上输出尾部,见 `background-jobs.md`。作业超时只终止等待本身,不会杀掉外部实例:醒来确认对方还在跑,再起一个等待作业即可。给等待作业一个明显长于预计耗时的 `timeout`,别让它每五分钟叫你一次。
41
+ 2. **稳定的完成态检测命令**:只有状态查询、没有阻塞等待时,按 `event-scheduling.md` 用 periodic + preAction 门控——对方忙就静默跳过,零 token。
42
+ 3. **wake 轮询(兜底)**:两者都没有时才用,`progress` 置 `waiting` + 合理 `wake`,醒来查状态、更新证据、必要时把 wake 推后。
43
+
44
+ 两种等待形态就这两个(本节是唯一真相源):**`waiting` 且无 `wake` = 停泊**,driver 不会来打扰,只有后台作业结束、用户消息或 `/tasks run` 会叫醒你;**`waiting` + `wake` = 定时回访**,到点由 driver 接续。
45
+
46
+ 无论走哪条,三条纪律不变:
47
+
48
+ 1. 委派时把工具、实例标识、工作目录/分支、预期产物和验收方法写进 task 正文,等谁、等什么写进 `blockedReason`。重启后这些是唯一能恢复现场的东西。
49
+ 2. 取回后自己 review 和验证。对方报告完成、进程退出码为 0、实例回到空闲,都不是验收证据。
50
+ 3. task 闭环前清理临时事件和外部实例。
45
51
 
46
52
  任何委派都不能转移最终交付责任。父代理必须确认成果已进入目标 checkout,而不是只停留在外部实例或口头报告中。
@@ -22,17 +22,19 @@ priority: 41
22
22
 
23
23
  以下生命周期动作本身就是原子 checkpoint,不要再追加 progress:`candidate`、`done`、`skip`、`cancel`。
24
24
 
25
- `verify` 只更新 control、不改正文。PASS 后若还要等外部审批(approval),用 `task_manage set wake=<合理时间>` 停留在 `verifying` 车道——**只改 wake、不换状态**,离开 verifying 会作废 PASS——并请用户 `/tasks approve <id>`。门禁的绑定规则见 `task-closeout.md`。除此之外不要用 `set` 代替正常进度日志。
25
+ `verify` 只更新 control、不改正文。验收与外部审批的全部门禁规则(PASS/approval 的绑定与失效、两个门并存时的顺序)以 `task-closeout.md` 为准,需要时读它,不要凭记忆推断。除此之外不要用 `set` 代替正常进度日志。
26
26
 
27
27
  ## 等待与继续
28
28
 
29
- - 等用户/外部系统/委派:`waiting` + 合理 `wake`,把等谁、等什么写进 `blockedReason`。
29
+ - 等一个会自己叫醒你的信号(后台作业结束、用户回话):`waiting` **且不设 `wake`** —— 这是停泊,driver 不会来打扰;等待形态的完整选择见 `task-delegation.md`。
30
+ - 等一个没人会通知的外部状态:`waiting` + 合理 `wake`,到点回访。
31
+ - 两者都把等谁、等什么写进 `blockedReason`。
30
32
  - 当前仍可继续:保持 `active`,清空 `wake`。
31
33
  - 明确停止:由用户 pause;不要用极远的 `wake` 模拟暂停。
32
34
 
33
35
  内建 driver 分钟级扫描 DingTalk `dm_*/group_*` channel,`wake` 到期后接续;无需 heartbeat、`.checkin` 或额外传感器。TUI 关闭后没有 daemon,不能自动唤醒。
34
36
 
35
- 有语义 checkpoint 时按较短 continuation delay 接续;只有用量变化、没有任务变化时按 stalled retry 退避。**不要为了拿到短退避而伪造 progress。**
37
+ 接续节奏由这一轮**实际做了什么**决定,不需要你去操纵:产生了可见 effect(write/edit/subagent/后台 job/给用户的回复,或一条跑通并有输出的同步 bash)就立即接续;只改了台账按 continuation delay;什么都没变按 stalled retry 退避。**不要为了拿到短退避而伪造 progress 或跑无意义命令**——真做事自然就快。
36
38
 
37
39
  ## 汇报与静默
38
40
 
@@ -55,9 +57,10 @@ priority: 41
55
57
 
56
58
  ## 不唤醒或频繁唤醒
57
59
 
58
- 可推进 = 非 done/cancelled/paused,且 `wake` 缺失、无效或已到期。
60
+ 可推进 = 非 done/cancelled/paused、非停泊(`waiting` 且无 `wake`),且 `wake` 缺失、无效或已到期。
59
61
 
60
- - `paused`:用户 `/tasks resume <id>`。
62
+ - 停泊中:这是有意的,等外部信号即可;确认没人会来叫时用 `/tasks run <id>` 或改回 `active`。
63
+ - `paused`:用户 `/tasks resume <id>`;若是治理器因预算耗尽暂停,得先 `/tasks set <id> attempts <n>` 放宽,否则 resume 会被拒绝。
61
64
  - `wake` 太远:纠正 `wake`;急催用 `/tasks run <id>`。
62
65
  - TUI 已关闭:没有 daemon,不能自动唤醒。
63
66
  - 反复空转:查最新 note 和 `nextAction`,修 Manual。
@@ -28,11 +28,11 @@ priority: 40
28
28
 
29
29
  - `priority` / `deadline`:表达调度重要性和硬期限,不用 `wake` 冒充 deadline。
30
30
  - `nextAction`:下一条可执行动作,避免写抽象愿望。
31
- - `maxAttempts`:唯一的按任务停止条件,按风险和规模收紧。它在**本周期、回合边界**检查,不会中断正在运行的单个回合。
31
+ - `maxAttempts`:唯一的按任务停止条件,默认 12,按风险和规模调整。它在**本周期、回合边界**检查,不会中断正在运行的单个回合。周期任务每开一个新周期清零,**一次性任务则是终身额度**——预计要十几步以上的长程任务,创建时就把它调高,不要等治理器把任务停掉再补。
32
32
  - `sideEffects`:`workspace` 或 `external`。发送、发布、部署、修改外部系统必须选 `external`,它会要求用户 `/tasks approve` 后才能 done。
33
33
  - 任务之间没有父子或依赖字段。需要表达先后次序时写进 `goal`/`manual`,或用 `wake` 把后续任务排到合适的时间;每个任务只按自己的 DoD 收尾。
34
34
 
35
- 外部副作用与独立验收并存时,DoD/Verification 要验收"**待执行动作及其输入已准备正确**"(内容、目标、参数、预演、回滚方案),不要把尚未获批的外部动作本身写成 candidate 前必须勾选的项——否则会形成"先执行才能勾选"与"先验收批准才能执行"的死循环。实际执行结果由审批记录和 done evidence 收口。
35
+ 外部副作用与独立验收并存时,DoD/Verification 只验收"**待执行动作及其输入已准备正确**",不要把尚未获批的外部动作本身写成必须勾选的项;理由与完整门禁顺序见 `task-closeout.md`。
36
36
 
37
37
  DoD 描述最终可验收结果,不把未执行动作写成 `[x] skipped`。存在条件分支时,用一个结果项表达“完成 A,或在条件不成立时交付 B 并附理由”;执行哪条路径由 evidence 证明。
38
38