create-principles-disciple 1.74.0 → 1.76.0

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 (63) hide show
  1. package/core/dist/runtime-v2/__tests__/architecture-regression.test.js +3 -3
  2. package/core/dist/runtime-v2/__tests__/architecture-regression.test.js.map +1 -1
  3. package/core/dist/runtime-v2/activation/index.d.ts +0 -2
  4. package/core/dist/runtime-v2/activation/index.d.ts.map +1 -1
  5. package/core/dist/runtime-v2/activation/index.js +0 -1
  6. package/core/dist/runtime-v2/activation/index.js.map +1 -1
  7. package/core/dist/runtime-v2/index.d.ts +4 -4
  8. package/core/dist/runtime-v2/index.d.ts.map +1 -1
  9. package/core/dist/runtime-v2/index.js +2 -2
  10. package/core/dist/runtime-v2/index.js.map +1 -1
  11. package/core/dist/runtime-v2/types/event-types.d.ts +3 -24
  12. package/core/dist/runtime-v2/types/event-types.d.ts.map +1 -1
  13. package/core/dist/runtime-v2/types/event-types.js +0 -10
  14. package/core/dist/runtime-v2/types/event-types.js.map +1 -1
  15. package/dist/utils/env.d.ts.map +1 -1
  16. package/dist/utils/env.js +0 -1
  17. package/dist/utils/env.js.map +1 -1
  18. package/package.json +1 -1
  19. package/plugin/dist/core/event-log.d.ts +1 -3
  20. package/plugin/dist/core/event-log.js +0 -6
  21. package/plugin/dist/core/migration.js +0 -1
  22. package/plugin/dist/core/path-resolver.js +0 -1
  23. package/plugin/dist/core/paths.d.ts +0 -1
  24. package/plugin/dist/core/paths.js +0 -1
  25. package/plugin/dist/hooks/gate-block-helper.js +17 -20
  26. package/plugin/dist/hooks/gate.js +12 -58
  27. package/plugin/dist/hooks/prompt.d.ts +6 -0
  28. package/plugin/dist/hooks/prompt.js +1 -56
  29. package/plugin/dist/types/event-types.d.ts +1 -1
  30. package/plugin/dist/utils/io.d.ts +0 -1
  31. package/plugin/dist/utils/io.js +0 -23
  32. package/plugin/templates/langs/en/core/AGENTS.md +5 -5
  33. package/plugin/templates/langs/en/principles/THINKING_OS.md +3 -2
  34. package/plugin/templates/langs/en/skills/evolve-task/SKILL.md +2 -2
  35. package/plugin/templates/langs/en/skills/pd-mentor/SKILL.md +1 -2
  36. package/plugin/templates/langs/zh/core/AGENTS.md +5 -5
  37. package/plugin/templates/langs/zh/principles/THINKING_OS.md +3 -2
  38. package/plugin/templates/langs/zh/skills/evolve-task/SKILL.md +2 -2
  39. package/plugin/templates/langs/zh/skills/pd-mentor/SKILL.md +1 -2
  40. package/plugin/templates/workspace/.principles/THINKING_OS.md +3 -2
  41. package/templates/langs/en/core/AGENTS.md +7 -7
  42. package/templates/langs/en/principles/THINKING_OS.md +3 -2
  43. package/templates/langs/en/skills/evolve-task/SKILL.md +3 -3
  44. package/templates/langs/en/skills/pd-mentor/SKILL.md +1 -2
  45. package/templates/langs/zh/core/AGENTS.md +7 -7
  46. package/templates/langs/zh/principles/THINKING_OS.md +3 -2
  47. package/templates/langs/zh/skills/evolve-task/SKILL.md +4 -4
  48. package/templates/langs/zh/skills/pd-mentor/SKILL.md +1 -2
  49. package/templates/workspace/.principles/THINKING_OS.md +3 -2
  50. package/core/dist/runtime-v2/__tests__/sqlite-confirm-first-state-store.test.d.ts +0 -2
  51. package/core/dist/runtime-v2/__tests__/sqlite-confirm-first-state-store.test.d.ts.map +0 -1
  52. package/core/dist/runtime-v2/__tests__/sqlite-confirm-first-state-store.test.js +0 -148
  53. package/core/dist/runtime-v2/__tests__/sqlite-confirm-first-state-store.test.js.map +0 -1
  54. package/core/dist/runtime-v2/activation/sqlite-confirm-first-state-store.d.ts +0 -22
  55. package/core/dist/runtime-v2/activation/sqlite-confirm-first-state-store.d.ts.map +0 -1
  56. package/core/dist/runtime-v2/activation/sqlite-confirm-first-state-store.js +0 -136
  57. package/core/dist/runtime-v2/activation/sqlite-confirm-first-state-store.js.map +0 -1
  58. package/plugin/dist/core/confirm-first-gate.d.ts +0 -59
  59. package/plugin/dist/core/confirm-first-gate.js +0 -215
  60. package/plugin/templates/langs/en/skills/plan-script/SKILL.md +0 -32
  61. package/plugin/templates/langs/zh/skills/plan-script/SKILL.md +0 -32
  62. package/templates/langs/en/skills/plan-script/SKILL.md +0 -32
  63. package/templates/langs/zh/skills/plan-script/SKILL.md +0 -32
@@ -15,7 +15,6 @@ export function migrateDirectoryStructure(api, workspaceDir) {
15
15
  { legacy: path.join(legacyDocsDir, 'PRINCIPLES.md'), newKey: 'PRINCIPLES' },
16
16
  { legacy: path.join(legacyDocsDir, 'THINKING_OS.md'), newKey: 'THINKING_OS' },
17
17
  { legacy: path.join(legacyDocsDir, 'DECISION_POLICY.json'), newKey: 'DECISION_POLICY' },
18
- { legacy: path.join(legacyDocsDir, 'PLAN.md'), newKey: 'PLAN' },
19
18
  { legacy: path.join(legacyDocsDir, 'evolution_queue.json'), newKey: 'EVOLUTION_QUEUE' },
20
19
  { legacy: path.join(legacyDocsDir, '.pain_flag'), newKey: 'PAIN_FLAG' },
21
20
  { legacy: path.join(legacyDocsDir, 'SYSTEM_CAPABILITIES.json'), newKey: 'SYSTEM_CAPABILITIES' },
@@ -240,7 +240,6 @@ export class PathResolver {
240
240
  'THINKING_OS': workspacePath.join(workspace, '.principles', 'THINKING_OS.md'),
241
241
  'DECISION_POLICY': workspacePath.join(workspace, '.principles', 'DECISION_POLICY.json'),
242
242
  'MODELS_DIR': workspacePath.join(workspace, '.principles', 'models'),
243
- 'PLAN': workspacePath.join(workspace, 'PLAN.md'),
244
243
  'AGENT_SCORECARD': workspacePath.join(state, 'AGENT_SCORECARD.json'),
245
244
  'PAIN_FLAG': workspacePath.join(state, '.pain_flag'),
246
245
  'EVOLUTION_QUEUE': workspacePath.join(state, 'evolution_queue.json'),
@@ -47,7 +47,6 @@ export declare const PD_FILES: {
47
47
  NOCTURNAL_MEMORY_DIR: string;
48
48
  NOCTURNAL_EXPORTS_DIR: string;
49
49
  IMPL_CODE_DIR: string;
50
- PLAN: string;
51
50
  MEMORY_MD: string;
52
51
  HEARTBEAT: string;
53
52
  SYSTEM_LOG: string;
@@ -61,7 +61,6 @@ export const PD_FILES = {
61
61
  NOCTURNAL_MEMORY_DIR: PD_DIRS.NOCTURNAL_MEMORY,
62
62
  NOCTURNAL_EXPORTS_DIR: PD_DIRS.NOCTURNAL_EXPORTS,
63
63
  IMPL_CODE_DIR: PD_DIRS.IMPL_CODE_DIR,
64
- PLAN: 'PLAN.md',
65
64
  MEMORY_MD: 'MEMORY.md',
66
65
  HEARTBEAT: 'HEARTBEAT.md',
67
66
  SYSTEM_LOG: posixJoin(PD_DIRS.LOGS, 'SYSTEM.log'),
@@ -115,34 +115,31 @@ export function recordGateBlockAndReturn(wctx, blockCtx, logger) {
115
115
  logger.info?.(`[PD_GATE] Gate block recorded without Runtime V2 diagnosis: ${gate.detail}`);
116
116
  }
117
117
  }
118
- // 6. Return consistent block result with operator guidance
118
+ // 6. Return consistent block result with contextual operator guidance
119
+ const blockMessage = buildContextualBlockMessage({ filePath, reason });
119
120
  return {
120
121
  block: true,
121
- blockReason: `[Principles Disciple] Security Gate Blocked this action.
122
+ blockReason: blockMessage,
123
+ };
124
+ }
125
+ /**
126
+ * Build contextual block message based on block source.
127
+ * - rule-host: principle-based guidance
128
+ * - default/gate: generic security gate message
129
+ */
130
+ function buildContextualBlockMessage({ filePath, reason, }) {
131
+ // rule-host or generic gate blocks
132
+ return `[Principles Disciple] Security Gate Blocked this action.
122
133
  File: ${filePath}
123
134
  Reason: ${reason}
124
135
 
125
136
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
126
137
  📋 How to unblock this operation:
127
138
 
128
- 1. Use the plan-script skill to create a PLAN.md:
129
- Invoke: skill:plan-script
130
-
131
- 2. Fill in the plan with:
132
- - Target Files: ${filePath}
133
- - Steps: What you want to do (be specific)
134
- - Metrics: How to verify success
135
- - Active Mental Models: Select 2 relevant models from .principles/THINKING_OS.md
136
- - Rollback: How to restore if it fails
137
-
138
- 3. After completing the plan, set STATUS: READY in PLAN.md
139
-
140
- 4. Retry the operation
141
-
142
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
143
- This is a mandatory security gate. The operation was blocked because the modification exceeds the allowed threshold for your current evolution tier.
144
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`,
145
- };
139
+ This action was blocked by a Rule Host principle.
140
+ If the blocked path is correct and safe, explain the reasoning to the owner
141
+ and ask for explicit confirmation to proceed.
142
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`;
146
143
  }
147
144
  /**
148
145
  * Schedule retry for trajectory gate block persistence.
@@ -8,15 +8,12 @@
8
8
  * 1. Early Return: Skip if not write/bash/agent tool or no workspace
9
9
  * 2. Rule Host: Dynamic principle-based evaluation (sole gate)
10
10
  */
11
- import * as fs from 'fs';
12
- import * as path from 'path';
13
- import { normalizePath, planStatus } from '../utils/io.js';
11
+ import { normalizePath } from '../utils/io.js';
14
12
  import { WorkspaceContext } from '../core/workspace-context.js';
15
13
  import { recordGateBlockAndReturn } from './gate-block-helper.js';
16
14
  import { RuleHost } from '../core/rule-host.js';
17
15
  import { validateCorrectionProposal, validateProposedPathBounds } from '@principles/core/runtime-v2';
18
16
  import { AGENT_TOOLS, BASH_TOOLS_SET, WRITE_TOOLS } from '../constants/tools.js';
19
- import { evaluateConfirmFirstGateSync } from '../core/confirm-first-gate.js';
20
17
  import { getSession, hasRecentThinking } from '../core/session-tracker.js';
21
18
  import { getEvolutionEngine } from '../core/evolution-engine.js';
22
19
  import { EventLogService } from '../core/event-log.js';
@@ -31,35 +28,6 @@ export function handleBeforeToolCall(event, ctx) {
31
28
  return;
32
29
  }
33
30
  const wctx = WorkspaceContext.fromHookContext(ctx);
34
- // 1.5. Confirm-First Gate — runs BEFORE filePath resolution to catch apply_patch/no-path cases
35
- try {
36
- const cfResult = evaluateConfirmFirstGateSync(ctx.sessionId, event.toolName, event.params);
37
- if (cfResult.action === 'block') {
38
- const eventLog = EventLogService.get(wctx.stateDir, logger);
39
- eventLog.recordConfirmFirstGateBlocked({
40
- sessionId: ctx.sessionId ?? 'unknown',
41
- workspaceDir: ctx.workspaceDir,
42
- toolName: event.toolName,
43
- reason: cfResult.reason ?? 'confirm_first_required',
44
- principleId: cfResult.principleId ?? 'unknown',
45
- nextAction: cfResult.nextAction ?? '',
46
- });
47
- // Use safe placeholder when filePath is unavailable (e.g., apply_patch with no path)
48
- const safePath = (event.params?.file_path || event.params?.path || event.params?.file || event.params?.target)
49
- ?? `<tool:${event.toolName}>`;
50
- return recordGateBlockAndReturn(wctx, {
51
- filePath: typeof safePath === 'string' ? safePath : `<tool:${event.toolName}>`,
52
- reason: cfResult.reason ?? 'confirm_first_required',
53
- toolName: event.toolName,
54
- sessionId: ctx.sessionId,
55
- blockSource: 'confirm-first-gate',
56
- }, logger);
57
- }
58
- }
59
- catch (cfErr) {
60
- // ERR-002: fail loud — log but do not crash the gate
61
- logger?.warn?.(`[PD:ConfirmFirst] Gate evaluation failed (non-blocking): ${String(cfErr)}`);
62
- }
63
31
  // 2. Resolve the target file path
64
32
  let filePath = event.params?.file_path || event.params?.path || event.params?.file || event.params?.target;
65
33
  // Heuristic for bash mutation detection
@@ -74,6 +42,11 @@ export function handleBeforeToolCall(event, ctx) {
74
42
  filePath = command;
75
43
  }
76
44
  }
45
+ // Write tools without a file path must still go through RuleHost evaluation.
46
+ // Use a synthetic path so RuleHost can evaluate and potentially block.
47
+ if (!filePath && isWriteTool) {
48
+ filePath = `<tool:${event.toolName}>`;
49
+ }
77
50
  if (typeof filePath !== 'string')
78
51
  return;
79
52
  const relPath = normalizePath(filePath, ctx.workspaceDir);
@@ -88,8 +61,12 @@ export function handleBeforeToolCall(event, ctx) {
88
61
  },
89
62
  workspace: {
90
63
  isRiskPath: false, // Rule Host determines risk dynamically
91
- planStatus: _getPlanStatus(ctx.workspaceDir),
92
- hasPlanFile: _hasPlanFile(ctx.workspaceDir),
64
+ // DEPRECATED (PRI-286): planStatus/hasPlanFile are legacy compatibility fields.
65
+ // Live PD no longer reads or manages PLAN.md state. These fields must not be
66
+ // used for new MVP behavior. Future "plan-first" enforcement must come from
67
+ // owner-approved RuleHost/code_tool_hook activation, not built-in state.
68
+ planStatus: 'NONE',
69
+ hasPlanFile: false,
93
70
  },
94
71
  session: {
95
72
  sessionId: ctx.sessionId,
@@ -353,29 +330,6 @@ function _extractParamsSummary(params) {
353
330
  summary.new_string = params.new_string;
354
331
  return summary;
355
332
  }
356
- function _getPlanStatus(workspaceDir) {
357
- try {
358
- const status = planStatus(workspaceDir);
359
- if (status === 'READY')
360
- return 'READY';
361
- if (status === 'DRAFT')
362
- return 'DRAFT';
363
- if (status === '')
364
- return 'NONE';
365
- return 'UNKNOWN';
366
- }
367
- catch {
368
- return 'UNKNOWN';
369
- }
370
- }
371
- function _hasPlanFile(workspaceDir) {
372
- try {
373
- return fs.existsSync(path.join(workspaceDir, 'PLAN.md'));
374
- }
375
- catch {
376
- return false;
377
- }
378
- }
379
333
  function _getCurrentGfi(sessionId) {
380
334
  if (!sessionId)
381
335
  return 0;
@@ -40,6 +40,12 @@ export declare function loadContextInjectionConfig(workspaceDir: string): Contex
40
40
  * @internal Helper for model configuration resolution
41
41
  */
42
42
  export declare function getDiagnosticianModel(api: PromptHookApi | null, logger?: PluginLogger): string;
43
+ /**
44
+ * Extract recent user messages for keyword optimization context.
45
+ */
46
+ /**
47
+ * Build prompt for keyword optimization subagent.
48
+ */
43
49
  export declare function handleBeforePromptBuild(event: PluginHookBeforePromptBuildEvent, ctx: PluginHookAgentContext & {
44
50
  api?: PromptHookApi;
45
51
  }): Promise<PluginHookBeforePromptBuildResult | void>;
@@ -4,11 +4,10 @@ import { clearInjectedProbationIds, getSession, resetFriction, setInjectedProbat
4
4
  import { WorkspaceContext } from '../core/workspace-context.js';
5
5
  import { defaultContextConfig } from '../types.js';
6
6
  import { classifyTask } from '../core/local-worker-routing.js';
7
- import { detectApprovalMarker, setConfirmFirstApproval, setConfirmFirstDirective, hydrateFromStore, pruneStoreStaleRows, setConfirmFirstStore, resetConfirmFirst } from '../core/confirm-first-gate.js';
8
7
  import { extractSummary, getHistoryVersions, parseWorkingMemorySection, workingMemoryToInjection, autoCompressFocus, safeReadCurrentFocus } from '../core/focus-history.js';
9
8
  import { PathResolver } from '../core/path-resolver.js';
10
9
  import { selectPrinciplesForInjection, DEFAULT_PRINCIPLE_BUDGET } from '../core/principle-injection.js';
11
- import { getCachedMaskedPrincipleSet, WorkflowFunnelLoader, PiAiRuntimeAdapter, EmpathyObserver, AgentScheduler, SqliteConfirmFirstStateStore, SqliteConnection } from '@principles/core/runtime-v2';
10
+ import { getCachedMaskedPrincipleSet, WorkflowFunnelLoader, PiAiRuntimeAdapter, EmpathyObserver, AgentScheduler } from '@principles/core/runtime-v2';
12
11
  import { truncateInjectionToBudget } from '@principles/core/prompt-builder';
13
12
  import { PromptActivationReader, RUNTIME_V2_PRINCIPLE_BUDGET } from '../core/runtime-v2-prompt-activation-reader.js';
14
13
  import { matchEmpathyKeywords, loadKeywordStore, saveKeywordStore, getKeywordStoreSummary, } from '../core/empathy-keyword-matcher.js';
@@ -51,7 +50,6 @@ function cachedReadFile(filePath) {
51
50
  // Module-level empathy state — shared across calls to avoid per-turn I/O
52
51
  let _empathyTurnCounter = 0;
53
52
  let _empathyKeywordCache = null;
54
- let _confirmFirstHydrationCounter = 0;
55
53
  /**
56
54
  * OpenClaw API Prompt Hook
57
55
  * Constructs the system prompt injected into LLM context for Principles Disciple
@@ -186,19 +184,6 @@ export function getDiagnosticianModel(api, logger) {
186
184
  /**
187
185
  * Build prompt for keyword optimization subagent.
188
186
  */
189
- function ensureConfirmFirstStore(workspaceDir) {
190
- if (!_confirmFirstStoreInitialized) {
191
- try {
192
- const connection = new SqliteConnection({ workspaceDir, readonly: false });
193
- setConfirmFirstStore(new SqliteConfirmFirstStateStore(connection));
194
- _confirmFirstStoreInitialized = true;
195
- }
196
- catch (err) {
197
- console.warn(`[PD:ConfirmFirst] Failed to initialize store: ${String(err)}`);
198
- }
199
- }
200
- }
201
- let _confirmFirstStoreInitialized = false;
202
187
  export async function handleBeforePromptBuild(event, ctx) {
203
188
  const { workspaceDir } = ctx;
204
189
  const logger = ctx.api?.logger;
@@ -213,17 +198,6 @@ export async function handleBeforePromptBuild(event, ctx) {
213
198
  if (sessionId) {
214
199
  wctx.trajectory?.recordSession?.({ sessionId });
215
200
  }
216
- if (sessionId) {
217
- ensureConfirmFirstStore(workspaceDir);
218
- hydrateFromStore(sessionId);
219
- _confirmFirstHydrationCounter++;
220
- if (_confirmFirstHydrationCounter % 100 === 0) {
221
- const pruned = pruneStoreStaleRows();
222
- if (pruned > 0) {
223
- logger?.info?.(`[PD:ConfirmFirst] Pruned ${pruned} stale rows from confirm_first_state`);
224
- }
225
- }
226
- }
227
201
  if (sessionId && trigger === 'user' && Array.isArray(event.messages) && event.messages.length > 0) {
228
202
  const latestUserIndex = [...event.messages]
229
203
  .map((message, index) => ({ message, index }))
@@ -231,25 +205,6 @@ export async function handleBeforePromptBuild(event, ctx) {
231
205
  .find((entry) => entry.message?.role === 'user');
232
206
  if (latestUserIndex) {
233
207
  const userText = getTextContent(latestUserIndex.message);
234
- // ── Confirm-first approval detection ──
235
- // If user sends approval language, mark session as approved for confirm-first gate
236
- if (sessionId && detectApprovalMarker(userText)) {
237
- setConfirmFirstApproval(sessionId);
238
- // P2: Emit approval telemetry for observability (ERR-002)
239
- try {
240
- wctx.eventLog.recordConfirmFirstGateApproved({
241
- sessionId,
242
- workspaceDir: wctx.workspaceDir,
243
- toolName: '(approval)',
244
- reason: 'user_approval_detected',
245
- principleId: 'confirm-first',
246
- nextAction: 'mutating tools now permitted',
247
- });
248
- }
249
- catch (logErr) {
250
- logger?.warn?.(`[PD:ConfirmFirst] Failed to emit approval event: ${String(logErr)}`);
251
- }
252
- }
253
208
  // Use CorrectionCueLearner for detection — supports learned keywords, not just hardcoded list
254
209
  let correctionCue = null;
255
210
  try {
@@ -839,19 +794,9 @@ ${heartbeatChecklist}
839
794
  catch (logErr) {
840
795
  logger?.warn?.(`[PD:RuntimeV2] Failed to emit activation observability event: ${String(logErr)}`);
841
796
  }
842
- // ── Set confirm-first directive state for gate enforcement ──
843
- if (sessionId) {
844
- const cfPrinciple = dedupedV2.find((p) => p.principleId === 'princ-mvp-acceptance-confirm-first' ||
845
- (p.text.toLowerCase().includes('confirm requirements') &&
846
- p.text.toLowerCase().includes('owner approval')));
847
- setConfirmFirstDirective(sessionId, !!cfPrinciple, cfPrinciple?.principleId);
848
- }
849
797
  }
850
798
  catch (e) {
851
799
  logger?.warn?.(`[PD:RuntimeV2] Failed to read Runtime V2 prompt activations: ${String(e)}`);
852
- if (sessionId) {
853
- resetConfirmFirst(sessionId);
854
- }
855
800
  }
856
801
  // Build appendSystemContext with recency effect
857
802
  // Content order (most important last): behavioral_constraints -> project_context -> working_memory -> reflection_log -> thinking_os -> principles
@@ -1,2 +1,2 @@
1
- export type { EventType, EventCategory, EventLogEntry, ToolCallEventData, PainSignalEventData, RuleMatchEventData, RulePromotionEventData, HookExecutionEventData, GateBlockEventData, GateBypassEventData, PlanApprovalEventData, EvolutionTaskEventData, EmpathyRollbackEventData, HeartbeatDiagnosisEventData, DiagnosisTaskEventData, DiagnosticianReportEventData, PrincipleCandidateEventData, RuleEnforcedEventData, RuleHostEvaluatedEventData, RuleHostBlockedEventData, RuleHostRequireApprovalEventData, RuleHostAutoCorrectProposedEventData, RuleHostAutoCorrectAppliedEventData, RuntimeV2PromptActivationsInjectedEventData, RuntimeV2ConfirmFirstGateEventData, ToolCallStats, ErrorStats, PainStats, EmpathyEventStats, GfiStats, EvolutionStats as EventEvolutionStats, HookStats, DailyStats, } from '@principles/core/runtime-v2';
1
+ export type { EventType, EventCategory, EventLogEntry, ToolCallEventData, PainSignalEventData, RuleMatchEventData, RulePromotionEventData, HookExecutionEventData, GateBlockEventData, GateBypassEventData, PlanApprovalEventData, EvolutionTaskEventData, EmpathyRollbackEventData, HeartbeatDiagnosisEventData, DiagnosisTaskEventData, DiagnosticianReportEventData, PrincipleCandidateEventData, RuleEnforcedEventData, RuleHostEvaluatedEventData, RuleHostBlockedEventData, RuleHostRequireApprovalEventData, RuleHostAutoCorrectProposedEventData, RuleHostAutoCorrectAppliedEventData, RuntimeV2PromptActivationsInjectedEventData, ToolCallStats, ErrorStats, PainStats, EmpathyEventStats, GfiStats, EvolutionStats as EventEvolutionStats, HookStats, DailyStats, } from '@principles/core/runtime-v2';
2
2
  export { createEmptyDailyStats, } from '@principles/core/runtime-v2';
@@ -4,7 +4,6 @@ export declare function normalizeRiskPath(p: string): string;
4
4
  export declare function isRisky(relPath: string, riskPaths: string[]): boolean;
5
5
  export declare function parseKvLines(text: string): Record<string, string>;
6
6
  export declare function serializeKvLines(data: Record<string, any>): string;
7
- export declare function planStatus(projectDir: string): string;
8
7
  /**
9
8
  * Normalize command arguments from PluginCommandContext.args.
10
9
  * Handles string | string[] | undefined union by joining arrays with spaces.
@@ -1,6 +1,5 @@
1
1
  import * as path from 'path';
2
2
  import * as fs from 'fs';
3
- import { resolvePdPath } from '../core/paths.js';
4
3
  /**
5
4
  * Atomic file write — write to temp then rename to prevent partial writes on crash.
6
5
  *
@@ -141,28 +140,6 @@ export function serializeKvLines(data) {
141
140
  }
142
141
  return lines.join('\n');
143
142
  }
144
- export function planStatus(projectDir) {
145
- const planPath = resolvePdPath(projectDir, 'PLAN');
146
- try {
147
- if (!fs.existsSync(planPath))
148
- return '';
149
- const content = fs.readFileSync(planPath, 'utf8');
150
- const lines = content.split('\n');
151
- for (const line of lines) {
152
- if (line.startsWith('STATUS:')) {
153
- const parts = line.split(':');
154
- if (parts.length > 1) {
155
- return parts[1].trim().split(/\s+/)[0] || '';
156
- }
157
- }
158
- }
159
- /* eslint-disable @typescript-eslint/no-unused-vars -- Reason: Error is intentionally ignored for graceful degradation */
160
- }
161
- catch (_e) {
162
- // Ignore read errors
163
- }
164
- return '';
165
- }
166
143
  /**
167
144
  * Normalize command arguments from PluginCommandContext.args.
168
145
  * Handles string | string[] | undefined union by joining arrays with spaces.
@@ -17,7 +17,6 @@ As Principles Disciple, you must distinguish between two physical spaces:
17
17
  Make decisions based on relative paths in the **Project Battlefield**:
18
18
 
19
19
  - **Strategic Focus**: `./memory/STRATEGY.md`
20
- - **Physical Plan**: `./PLAN.md`
21
20
  - **Pain Signal**: Runtime V2 `PainSignalBridge` (`pd pain record` for manual trigger; `.state/.pain_flag` is legacy compatibility only)
22
21
  - **System Capabilities**: `./.state/SYSTEM_CAPABILITIES.json`
23
22
 
@@ -166,12 +165,13 @@ On platforms that support reactions (Discord, Slack), use emoji reactions natura
166
165
  You default to architect mode.
167
166
 
168
167
  - **L1 (Direct Execution)**: Single-file tweaks, doc maintenance → do it directly
169
- - **L2 (Delegation Protocol)**: Major changes → **MUST** update `./PLAN.md` and use `pd_spawn_agent` tool
168
+ - **L2 (Delegation Protocol)**: Major changes → recommended to describe the plan and get owner confirmation before executing
170
169
 
171
- ### State Machine Gating
170
+ ### Planning Guidance
172
171
 
173
- - **Single source of truth**: `./PLAN.md`
174
- - **Physical interception**: Plugin activated. If `PLAN.md` is not `READY` and you attempt to modify risk paths, calls will be blocked
172
+ - For complex tasks, consider drafting a plan document and getting owner approval before making large changes
173
+ - This is a behavioral suggestion, not a built-in gate PD does not enforce plan-before-action by default
174
+ - If an owner-approved RuleHost rule enforces planning behavior, that rule takes effect automatically
175
175
  - **Prevent pollution**: Never write execution details back to strategic documents
176
176
 
177
177
  ---
@@ -39,8 +39,9 @@ LLMs are highly sensitive to XML tags; this structure is designed to boost instr
39
39
  <!-- 执行与物理限制 (Execution & Physical Constraints) -->
40
40
  <directive id="T-05" name="PHYSICAL_DEFENSE_AND_ORCHESTRATION">
41
41
  <trigger>When asked to perform a major refactoring, multi-file change (>2 files), or an architectural shift.</trigger>
42
- <must>Limit your blast radius. You MUST draft a `PLAN.md` (status: READY). After any code change, you MUST run canary tests (e.g., `npm test`, linters) to verify integrity.</must>
43
- <forbidden>Executing large-scale unstructured changes directly without a plan, or skipping post-modification validation.</forbidden>
42
+ <should>For complex changes, describe your plan and get owner confirmation before executing.</should>
43
+ <must>Limit your blast radius. After any code change, you MUST run canary tests (e.g., `npm test`, linters) to verify integrity.</must>
44
+ <forbidden>Executing large-scale unstructured changes directly, or skipping post-modification validation.</forbidden>
44
45
  </directive>
45
46
 
46
47
  <directive id="T-06" name="OCCAMS_RAZOR_MVC">
@@ -51,7 +51,7 @@ Output:
51
51
 
52
52
  ## Step 6: Delegate Planner (Movie Script Plan)
53
53
  - Planner outputs Plan (steps/commands/metrics/rollback).
54
- - Write plan to PLAN.md (STATUS line must exist).
54
+ - Write plan to a planning document for owner review.
55
55
  - **Task Sync**:
56
56
  - If `CLAUDE_CODE_TASK_LIST_ID` is set, you must convert the Plan's core steps to Native Tasks (via natural language command "Add task..." or related tools).
57
57
  - If not set and in interactive mode, prompt user: "Recommend running `export CLAUDE_CODE_TASK_LIST_ID=task-$(date +%s)` to enable persistent task tracking."
@@ -59,7 +59,7 @@ Output:
59
59
  - **Performance Evaluation**: After task completion, write to `.state/.verdict.json`. Format follows `@.principles/schemas/agent_verdict_schema.json`.
60
60
 
61
61
  ## Step 7: Delegate Implementer (Execution)
62
- - Implementer can only execute according to PLAN. Any deviation must first update PLAN.
62
+ - Implementer executes according to the plan from Step 6. Any deviation must first be approved by updating the plan.
63
63
  - **Performance Evaluation**: After task completion, write to `.state/.verdict.json` based on verification results. Format follows `@.principles/schemas/agent_verdict_schema.json`.
64
64
 
65
65
  ## Step 8: Delegate Reviewer (Review)
@@ -185,7 +185,7 @@ For complex scenarios, combine multiple skills:
185
185
 
186
186
  | Scenario | Combined Flow |
187
187
  |----------|---------------|
188
- | Major refactor | `/pd-evolve` → `plan-script` → `deductive-audit` → execute |
188
+ | Major refactor | `/pd-evolve` → `deductive-audit` → execute |
189
189
  | System optimization | `/pd-status` → `evolve-system` → `root-cause` |
190
190
  | Project review | `/pd-daily` → `/pd-okr` → `reflection-log` |
191
191
 
@@ -196,7 +196,6 @@ These skills are usually called automatically by the system, but advanced users
196
196
  - `triage` - Issue triage
197
197
  - `root-cause` - Root cause analysis
198
198
  - `deductive-audit` - Deductive audit
199
- - `plan-script` - Plan orchestration
200
199
  - `reflection` - Metacognitive reflection
201
200
  - `reflection-log` - Reflection logging
202
201
 
@@ -17,7 +17,6 @@
17
17
  基于**项目战场**中的相对路径进行决策:
18
18
 
19
19
  - **项目最高战略**: `./memory/STRATEGY.md`
20
- - **项目物理计划**: `./PLAN.md`
21
20
  - **痛觉反射信号**: Runtime V2 `PainSignalBridge`(手动触发使用 `pd pain record`;`.state/.pain_flag` 仅为 legacy compatibility)
22
21
  - **系统能力快照**: `./.state/SYSTEM_CAPABILITIES.json`
23
22
 
@@ -158,12 +157,13 @@
158
157
  你默认处于架构师模式。
159
158
 
160
159
  - **L1 (直接执行)**:单文件微调、文档维护 → 直接操作
161
- - **L2 (委派协议)**:重大变更 → **必须**更新 `./PLAN.md` 并使用 `pd_spawn_agent` 工具委派任务
160
+ - **L2 (委派协议)**:重大变更 → 建议先描述计划并获得 owner 确认后再执行
162
161
 
163
- ### 状态机门禁 (State Machine Gating)
162
+ ### 计划引导 (Planning Guidance)
164
163
 
165
- - **唯一事实源**:`./PLAN.md`
166
- - **物理拦截**:插件已激活。若 `PLAN.md` `READY` 且尝试修改风险路径,调用将被阻断
164
+ - 对复杂任务,建议先起草计划文档并获得 owner 批准后再做大幅修改
165
+ - 这是行为建议,不是内置门禁 PD 默认不强制"先计划后执行"
166
+ - 若 owner 批准的 RuleHost 规则强制了计划行为,该规则会自动生效
167
167
  - **防止污染**:禁止将执行层细节写回战略文档
168
168
 
169
169
  ---
@@ -39,8 +39,9 @@
39
39
  <!-- 执行与物理限制 (Execution & Physical Constraints) -->
40
40
  <directive id="T-05" name="PHYSICAL_DEFENSE_AND_ORCHESTRATION">
41
41
  <trigger>当被要求执行大型重构、多文件修改(>2 个文件)或架构变更时。</trigger>
42
- <must>限制爆炸半径。你必须起草一个 `PLAN.md`(状态:READY)。在修改任何代码后,必须运行金丝雀测试(例如 `npm test`、linters)以验证完整性。</must>
43
- <forbidden>在没有计划的情况下直接执行大规模非结构化变更,或跳过修改后的验证环节。</forbidden>
42
+ <should>对复杂变更,先描述计划并获得 owner 确认后再执行。</should>
43
+ <must>限制爆炸半径。在修改任何代码后,必须运行金丝雀测试(例如 `npm test`、linters)以验证完整性。</must>
44
+ <forbidden>直接执行大规模非结构化变更,或跳过修改后的验证环节。</forbidden>
44
45
  </directive>
45
46
 
46
47
  <directive id="T-06" name="OCCAMS_RAZOR_MVC">
@@ -51,7 +51,7 @@ disable-model-invocation: true
51
51
 
52
52
  ## Step 6: 委派 Planner(电影剧本计划)
53
53
  - Planner 输出 Plan(步骤/命令/指标/回滚)。
54
- - 将计划写入 PLAN.md(STATUS 行必须存在)。
54
+ - 将计划写入计划文档供 owner 审阅。
55
55
  - **任务同步 (Task Sync)**:
56
56
  - 如果 `CLAUDE_CODE_TASK_LIST_ID` 已设置,你必须将上述 Plan 的核心步骤直接转化为 Native Tasks(通过自然语言指令"Add task..."或相关工具)。
57
57
  - 如果未设置且为交互模式,提示用户:"建议运行 `export CLAUDE_CODE_TASK_LIST_ID=task-$(date +%s)` 以启用持久化任务追踪。"
@@ -59,7 +59,7 @@ disable-model-invocation: true
59
59
  - **绩效评估**: 任务完成后,写入 `.state/.verdict.json`。格式遵循 `@.principles/schemas/agent_verdict_schema.json`。
60
60
 
61
61
  ## Step 7: 委派 Implementer(执行)
62
- - Implementer 只能按 PLAN 执行。任何偏离必须先更新 PLAN。
62
+ - Implementer 按照 Step 6 的计划执行。任何偏离必须先更新计划并获得确认。
63
63
  - **绩效评估**: 任务完成后,根据验证结果写入 `.state/.verdict.json`。格式遵循 `@.principles/schemas/agent_verdict_schema.json`。
64
64
 
65
65
  ## Step 8: 委派 Reviewer(审查)
@@ -185,7 +185,7 @@ disable-model-invocation: true
185
185
 
186
186
  | 场景 | 组合流程 |
187
187
  |------|----------|
188
- | 大型重构 | `/pd-evolve` → `plan-script` → `deductive-audit` → 执行 |
188
+ | 大型重构 | `/pd-evolve` → `deductive-audit` → 执行 |
189
189
  | 系统优化 | `/pd-status` → `evolve-system` → `root-cause` |
190
190
  | 项目复盘 | `/pd-daily` → `/pd-okr` → `reflection-log` |
191
191
 
@@ -196,7 +196,6 @@ disable-model-invocation: true
196
196
  - `triage` - 问题分诊
197
197
  - `root-cause` - 根因分析
198
198
  - `deductive-audit` - 演绎审计
199
- - `plan-script` - 计划编排
200
199
  - `reflection` - 元认知反思
201
200
  - `reflection-log` - 反思落盘
202
201
 
@@ -39,8 +39,9 @@
39
39
  <!-- 执行与物理限制 (Execution & Physical Constraints) -->
40
40
  <directive id="T-05" name="PHYSICAL_DEFENSE_AND_ORCHESTRATION">
41
41
  <trigger>当被要求执行大型重构、多文件修改(>2 个文件)或架构变更时。</trigger>
42
- <must>限制爆炸半径。你必须起草一个 `PLAN.md`(状态:READY)。在修改任何代码后,必须运行金丝雀测试(例如 `npm test`、linters)以验证完整性。</must>
43
- <forbidden>在没有计划的情况下直接执行大规模非结构化变更,或跳过修改后的验证环节。</forbidden>
42
+ <should>对复杂变更,先描述计划并获得 owner 确认后再执行。</should>
43
+ <must>限制爆炸半径。在修改任何代码后,必须运行金丝雀测试(例如 `npm test`、linters)以验证完整性。</must>
44
+ <forbidden>直接执行大规模非结构化变更,或跳过修改后的验证环节。</forbidden>
44
45
  </directive>
45
46
 
46
47
  <directive id="T-06" name="OCCAMS_RAZOR_MVC">
@@ -17,8 +17,7 @@ As Principles Disciple, you must distinguish between two physical spaces:
17
17
  Make decisions based on relative paths in the **Project Battlefield**:
18
18
 
19
19
  - **Strategic Focus**: `./memory/STRATEGY.md`
20
- - **Physical Plan**: `./PLAN.md`
21
- - **Pain Signal**: `./.state/.pain_flag`
20
+ - **Pain Signal**: Runtime V2 `PainSignalBridge` (`pd pain record` for manual trigger; `.state/.pain_flag` is legacy compatibility only)
22
21
  - **System Capabilities**: `./.state/SYSTEM_CAPABILITIES.json`
23
22
 
24
23
  ---
@@ -72,7 +71,7 @@ When you receive a heartbeat poll, don't just reply `HEARTBEAT_OK` every time. U
72
71
 
73
72
  ### What to Check (rotate through these):
74
73
 
75
- - **Pain & Evolution**: Check `.pain_flag`, `EVOLUTION_QUEUE.json`
74
+ - **Pain & Evolution**: Check Runtime V2 diagnostics (`pd pain record`, candidates, ledger) and `EVOLUTION_QUEUE.json`; `.pain_flag` is legacy compatibility only
76
75
  - **Strategic Alignment**: Compare against `CURRENT_FOCUS.md`
77
76
  - **Environment Health**: Tool chain status, project root cleanliness
78
77
 
@@ -166,12 +165,13 @@ On platforms that support reactions (Discord, Slack), use emoji reactions natura
166
165
  You default to architect mode.
167
166
 
168
167
  - **L1 (Direct Execution)**: Single-file tweaks, doc maintenance → do it directly
169
- - **L2 (Delegation Protocol)**: Major changes → **MUST** update `./PLAN.md` and use `pd_spawn_agent` tool
168
+ - **L2 (Delegation Protocol)**: Major changes → recommended to describe the plan and get owner confirmation before executing
170
169
 
171
- ### State Machine Gating
170
+ ### Planning Guidance
172
171
 
173
- - **Single source of truth**: `./PLAN.md`
174
- - **Physical interception**: Plugin activated. If `PLAN.md` is not `READY` and you attempt to modify risk paths, calls will be blocked
172
+ - For complex tasks, consider drafting a plan document and getting owner approval before making large changes
173
+ - This is a behavioral suggestion, not a built-in gate PD does not enforce plan-before-action by default
174
+ - If an owner-approved RuleHost rule enforces planning behavior, that rule takes effect automatically
175
175
  - **Prevent pollution**: Never write execution details back to strategic documents
176
176
 
177
177
  ---
@@ -39,8 +39,9 @@ LLMs are highly sensitive to XML tags; this structure is designed to boost instr
39
39
  <!-- 执行与物理限制 (Execution & Physical Constraints) -->
40
40
  <directive id="T-05" name="PHYSICAL_DEFENSE_AND_ORCHESTRATION">
41
41
  <trigger>When asked to perform a major refactoring, multi-file change (>2 files), or an architectural shift.</trigger>
42
- <must>Limit your blast radius. You MUST draft a `PLAN.md` (status: READY). After any code change, you MUST run canary tests (e.g., `npm test`, linters) to verify integrity.</must>
43
- <forbidden>Executing large-scale unstructured changes directly without a plan, or skipping post-modification validation.</forbidden>
42
+ <should>For complex changes, describe your plan and get owner confirmation before executing.</should>
43
+ <must>Limit your blast radius. After any code change, you MUST run canary tests (e.g., `npm test`, linters) to verify integrity.</must>
44
+ <forbidden>Executing large-scale unstructured changes directly, or skipping post-modification validation.</forbidden>
44
45
  </directive>
45
46
 
46
47
  <directive id="T-06" name="OCCAMS_RAZOR_MVC">
@@ -10,7 +10,7 @@ You must execute the following steps in order (no skipping). ARGUMENTS: $ARGUMEN
10
10
  - Read the last entry in memory/CHECKPOINT.md
11
11
  - Read the last 3 entries in memory/ISSUE_LOG.md
12
12
  - Read recent decisions in memory/DECISIONS.md
13
- - If .state/.pain_flag exists, handle breakpoint recovery first
13
+ - Runtime V2 pain diagnosis uses task input/context, not `.state/.pain_flag`
14
14
 
15
15
  ## Step 1: Read Runtime Parameters & Self-Check
16
16
  - Read .principles/PROFILE.json, understand risk_paths, gate, tests.commands.
@@ -51,7 +51,7 @@ Output:
51
51
 
52
52
  ## Step 6: Delegate Planner (Movie Script Plan)
53
53
  - Planner outputs Plan (steps/commands/metrics/rollback).
54
- - Write plan to PLAN.md (STATUS line must exist).
54
+ - Write plan to a planning document for owner review.
55
55
  - **Task Sync**:
56
56
  - If `CLAUDE_CODE_TASK_LIST_ID` is set, you must convert the Plan's core steps to Native Tasks (via natural language command "Add task..." or related tools).
57
57
  - If not set and in interactive mode, prompt user: "Recommend running `export CLAUDE_CODE_TASK_LIST_ID=task-$(date +%s)` to enable persistent task tracking."
@@ -59,7 +59,7 @@ Output:
59
59
  - **Performance Evaluation**: After task completion, write to `.state/.verdict.json`. Format follows `@.principles/schemas/agent_verdict_schema.json`.
60
60
 
61
61
  ## Step 7: Delegate Implementer (Execution)
62
- - Implementer can only execute according to PLAN. Any deviation must first update PLAN.
62
+ - Implementer executes according to the plan from Step 6. Any deviation must first be approved by updating the plan.
63
63
  - **Performance Evaluation**: After task completion, write to `.state/.verdict.json` based on verification results. Format follows `@.principles/schemas/agent_verdict_schema.json`.
64
64
 
65
65
  ## Step 8: Delegate Reviewer (Review)
@@ -185,7 +185,7 @@ For complex scenarios, combine multiple skills:
185
185
 
186
186
  | Scenario | Combined Flow |
187
187
  |----------|---------------|
188
- | Major refactor | `/pd-evolve` → `plan-script` → `deductive-audit` → execute |
188
+ | Major refactor | `/pd-evolve` → `deductive-audit` → execute |
189
189
  | System optimization | `/pd-status` → `evolve-system` → `root-cause` |
190
190
  | Project review | `/pd-daily` → `/pd-okr` → `reflection-log` |
191
191
 
@@ -196,7 +196,6 @@ These skills are usually called automatically by the system, but advanced users
196
196
  - `triage` - Issue triage
197
197
  - `root-cause` - Root cause analysis
198
198
  - `deductive-audit` - Deductive audit
199
- - `plan-script` - Plan orchestration
200
199
  - `reflection` - Metacognitive reflection
201
200
  - `reflection-log` - Reflection logging
202
201