@fractaal/pi-goal-x 0.20.1 → 0.28.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 (95) hide show
  1. package/README.md +42 -290
  2. package/dist/goal-auditor.d.ts +7 -61
  3. package/dist/goal-auditor.js +98 -300
  4. package/dist/goal-auditor.js.map +1 -1
  5. package/dist/goal-contract.d.ts +205 -0
  6. package/dist/goal-contract.js +135 -0
  7. package/dist/goal-contract.js.map +1 -0
  8. package/dist/goal-transcript-events.d.ts +54 -0
  9. package/dist/goal-transcript-events.js +177 -0
  10. package/dist/goal-transcript-events.js.map +1 -0
  11. package/dist/goal-widget.d.ts +13 -0
  12. package/dist/goal-widget.js +45 -0
  13. package/dist/goal-widget.js.map +1 -0
  14. package/dist/goal.d.ts +8 -49
  15. package/dist/goal.js +519 -3643
  16. package/dist/goal.js.map +1 -1
  17. package/dist/legacy-migration.d.ts +61 -0
  18. package/dist/legacy-migration.js +306 -0
  19. package/dist/legacy-migration.js.map +1 -0
  20. package/docs/architecture.md +14 -232
  21. package/extensions/goal-auditor.ts +108 -363
  22. package/extensions/goal-contract.ts +149 -0
  23. package/extensions/goal-transcript-events.ts +194 -0
  24. package/extensions/goal-widget.ts +50 -0
  25. package/extensions/goal.ts +557 -3927
  26. package/extensions/legacy-migration.ts +340 -0
  27. package/package.json +46 -19
  28. package/dist/goal-compaction.d.ts +0 -10
  29. package/dist/goal-compaction.js +0 -104
  30. package/dist/goal-compaction.js.map +0 -1
  31. package/dist/goal-core.d.ts +0 -19
  32. package/dist/goal-core.js +0 -66
  33. package/dist/goal-core.js.map +0 -1
  34. package/dist/goal-draft.d.ts +0 -71
  35. package/dist/goal-draft.js +0 -201
  36. package/dist/goal-draft.js.map +0 -1
  37. package/dist/goal-ledger.d.ts +0 -139
  38. package/dist/goal-ledger.js +0 -306
  39. package/dist/goal-ledger.js.map +0 -1
  40. package/dist/goal-policy.d.ts +0 -127
  41. package/dist/goal-policy.js +0 -359
  42. package/dist/goal-policy.js.map +0 -1
  43. package/dist/goal-pool.d.ts +0 -17
  44. package/dist/goal-pool.js +0 -85
  45. package/dist/goal-pool.js.map +0 -1
  46. package/dist/goal-questionnaire.d.ts +0 -56
  47. package/dist/goal-questionnaire.js +0 -733
  48. package/dist/goal-questionnaire.js.map +0 -1
  49. package/dist/goal-record.d.ts +0 -94
  50. package/dist/goal-record.js +0 -155
  51. package/dist/goal-record.js.map +0 -1
  52. package/dist/goal-settings.d.ts +0 -56
  53. package/dist/goal-settings.js +0 -184
  54. package/dist/goal-settings.js.map +0 -1
  55. package/dist/goal-tool-names.d.ts +0 -20
  56. package/dist/goal-tool-names.js +0 -69
  57. package/dist/goal-tool-names.js.map +0 -1
  58. package/dist/prompts/goal-prompts.d.ts +0 -17
  59. package/dist/prompts/goal-prompts.js +0 -304
  60. package/dist/prompts/goal-prompts.js.map +0 -1
  61. package/dist/storage/goal-files.d.ts +0 -40
  62. package/dist/storage/goal-files.js +0 -320
  63. package/dist/storage/goal-files.js.map +0 -1
  64. package/dist/widgets/goal-escape-dialog.d.ts +0 -15
  65. package/dist/widgets/goal-escape-dialog.js +0 -118
  66. package/dist/widgets/goal-escape-dialog.js.map +0 -1
  67. package/dist/widgets/goal-notifications.d.ts +0 -5
  68. package/dist/widgets/goal-notifications.js +0 -9
  69. package/dist/widgets/goal-notifications.js.map +0 -1
  70. package/dist/widgets/goal-widget.d.ts +0 -58
  71. package/dist/widgets/goal-widget.js +0 -282
  72. package/dist/widgets/goal-widget.js.map +0 -1
  73. package/dist/widgets/task-list-overlay.d.ts +0 -8
  74. package/dist/widgets/task-list-overlay.js +0 -321
  75. package/dist/widgets/task-list-overlay.js.map +0 -1
  76. package/docs/agent-flow-design.md +0 -432
  77. package/docs/agentic-runtime-prd.md +0 -764
  78. package/docs/goal-ts-refactor-test-strategy.md +0 -82
  79. package/docs/pi-autoresearch-survey.md +0 -45
  80. package/extensions/goal-compaction.ts +0 -133
  81. package/extensions/goal-core.ts +0 -77
  82. package/extensions/goal-draft.ts +0 -263
  83. package/extensions/goal-ledger.ts +0 -354
  84. package/extensions/goal-policy.ts +0 -389
  85. package/extensions/goal-pool.ts +0 -98
  86. package/extensions/goal-questionnaire.ts +0 -779
  87. package/extensions/goal-record.ts +0 -256
  88. package/extensions/goal-settings.ts +0 -181
  89. package/extensions/goal-tool-names.ts +0 -76
  90. package/extensions/prompts/goal-prompts.ts +0 -308
  91. package/extensions/storage/goal-files.ts +0 -352
  92. package/extensions/widgets/goal-escape-dialog.ts +0 -146
  93. package/extensions/widgets/goal-notifications.ts +0 -9
  94. package/extensions/widgets/goal-widget.ts +0 -378
  95. package/extensions/widgets/task-list-overlay.ts +0 -389
@@ -1,82 +0,0 @@
1
- # Refactor and Test Baseline
2
-
3
- This document records the current safety net for the `pi-goal` componentization work.
4
-
5
- ## Commands
6
-
7
- ```bash
8
- npm test
9
- npm run check
10
- npm pack --dry-run
11
- ```
12
-
13
- ## Unit test coverage
14
-
15
- The fast local suite uses Node's built-in `node:test` runner and currently covers the core modules across:
16
-
17
- - `tests/goal-core.test.ts`
18
- - `tests/goal-draft.test.ts`
19
- - `tests/goal-policy.test.ts`
20
- - `tests/goal-questionnaire.test.ts`
21
- - `tests/goal-tool-names.test.ts`
22
- - `tests/goal-record.test.ts`
23
- - `tests/goal-files.test.ts`
24
- - `tests/goal-pool.test.ts`
25
- - `tests/goal-prompts.test.ts`
26
- - `tests/goal-notifications.test.ts`
27
- - `tests/goal-widget.test.ts`
28
-
29
- ## Extracted modules
30
-
31
- `extensions/goal.ts` remains the orchestration layer. The following logic has been extracted and covered by tests:
32
-
33
- | Module | Covered behavior |
34
- |---|---|
35
- | `extensions/goal-record.ts` | Goal creation, normalization/migration, usage cloning, persisted record shape |
36
- | `extensions/goal-pool.ts` | Open-goal pool creation, deterministic ordering, explicit-null/stale focus resolution, disk-wins legacy migration, disk lifecycle reconciliation helpers, list and selector labels, unfocused summaries |
37
- | `extensions/goal-core.ts` | Compact duration/token/status display, objective-title cleanup |
38
- | `extensions/goal-draft.ts` | Lightweight confirmation prompt, draft summary, safe objective escaping, focus/mode gate, Sisyphus prompt-style guidance, drafting tool gate, multi-open draft creation allowance |
39
- | `extensions/goal-policy.ts` | Creation/completion-from-active-or-paused, abort/pause/resume/clear policy, multi-open creation slot allowance, compaction reminder, full creation/completion reports |
40
- | `extensions/goal-auditor.ts` | Independent pi auditor agent config parsing, prompt construction, approval marker parsing, and completion audit execution |
41
- | `extensions/goal-questionnaire.ts` | Question normalization, duplicate id handling, option filtering, recommended-index validation, answer formatting, confirm/cancel mapping, `goal_question` and `goal_questionnaire` registration |
42
- | `extensions/goal-tool-names.ts` | Published tool constants, active/paused/drafting tool lists, goal work-tool list, progress-tool list for empty-turn gating, post-stop allowlist, question-like tool detection |
43
- | `extensions/prompts/goal-prompts.ts` | Active-goal, continuation, tweak-drafting, stale-checkpoint, and unfocused multi-open prompt text |
44
- | `extensions/storage/goal-files.ts` | Safe goal paths, serialize/parse round trip, prompt-body disk edits, active-goal scans, active/archive writes |
45
- | `extensions/widgets/goal-widget.ts` | Goal Beacon rendering, Sisyphus style label, status/path lines, blocker/suggested-action display, `+N open` and unfocused guidance |
46
- | `extensions/widgets/goal-notifications.ts` | Widget-style notification text for goal lifecycle toasts |
47
-
48
- ## Refactor rule
49
-
50
- 1. Add or update tests before moving behavior.
51
- 2. Extract pure helpers or narrow adapter boundaries first.
52
- 3. Keep published tool names, slash commands, file formats, and UI semantics stable unless the user explicitly asks for a new public affordance such as `/goal-abort` or `abort_goal`.
53
- 4. Run `npm test` and `npm run check` after each slice.
54
- 5. Run `npm pack --dry-run` before release or packaging changes.
55
-
56
- ## Remaining runtime-sensitive areas
57
-
58
- The following remain intentionally in `goal.ts` until a stronger mock `ExtensionAPI` / `ExtensionContext` harness exists:
59
-
60
- - pi command registration;
61
- - tool registration beyond the questionnaire pair;
62
- - session event hooks;
63
- - timers and auto-continue scheduling;
64
- - live TUI widget rendering.
65
-
66
- These areas are protected by TypeScript, focused unit helpers, and the end-to-end experiment harness rather than isolated component tests.
67
-
68
- ## Multi-goal focus test notes
69
-
70
- The current suite specifically covers the multi-open goal architecture through pure helpers and storage seams:
71
-
72
- - focus entry normalization in `tests/goal-record.test.ts`;
73
- - active goal file scanning and invalid/symlink filtering in `tests/goal-files.test.ts`;
74
- - goal pool sorting, focus resolution, explicit no-focus/stale focus behavior, disk-wins legacy fallback, disk lifecycle merge, list output, and selector labels in `tests/goal-pool.test.ts`;
75
- - multi-open draft creation allowance, missing confirmation intent rejection, deprecated `draftId` compatibility, concrete-topic direct proposal guidance, and lightweight confirmation prompt text in `tests/goal-draft.test.ts`;
76
- - no-focus prompt guidance in `tests/goal-prompts.test.ts`;
77
- - continuation and compaction policy in `tests/goal-policy.test.ts`;
78
- - auditor marker/config/prompt behavior in `tests/goal-auditor.test.ts`;
79
- - drafting-phase lifecycle-tool suspension and progress-tool exclusion of `get_goal`, question tools, and draft proposal tools in `tests/goal-tool-names.test.ts`;
80
- - focused widget `+N open` and unfocused `/goal-focus` guidance in `tests/goal-widget.test.ts`.
81
-
82
- Release is intentionally separate from implementation validation. The local validation gate is `npm test`, `npm run check`, `npm pack --dry-run`, and `git diff --check`; `npm version`, `npm publish`, `git push`, and `pi update` only happen on explicit release request.
@@ -1,45 +0,0 @@
1
- # Implemented Borrowed Patterns
2
-
3
- This document records external patterns that are actually implemented in `pi-goal` today.
4
-
5
- ## From pi-codex-goal
6
-
7
- `pi-goal` uses several goal-loop stability patterns inspired by `pi-codex-goal`:
8
-
9
- - **Goal-id continuation markers**: continuation prompts include a goal id so stale prompts can be detected.
10
- - **Context interceptor**: stale continuation context is neutralized instead of letting an old goal keep driving the agent.
11
- - **Abort pause**: user abort / Ctrl-C pauses the active goal rather than leaving it in a misleading active state.
12
- - **Disk-backed active goal file**: the current objective is materialized on disk and can be audited outside the chat.
13
-
14
- ## From pi-autoresearch
15
-
16
- `pi-goal` uses several autonomous-loop safety patterns inspired by `pi-autoresearch`:
17
-
18
- - **Empty-turn gate**: auto-continue does not advance when the agent did no meaningful goal-work tool activity.
19
- - **Post-compaction reminder**: after compaction, the next agent turn is reminded to re-read the objective and continue from actual artifacts/state.
20
-
21
- ## pi-goal-specific work
22
-
23
- The current extension also adds behavior specific to goal drafting and lifecycle safety:
24
-
25
- - **Intent-before-run**: `/goals` and `/sisyphus` start a drafting discussion instead of immediate execution.
26
- - **Direct set shortcut**: `/goals-set` and `/sisyphus-set` immediately create a goal when the user already knows the final objective.
27
- - **Confirm-before-commit for discussions**: `propose_goal_draft` is the normal discussion-based creation path; `create_goal` stays hidden.
28
- - **Sisyphus as style**: `/sisyphus` and `/sisyphus-set` use the same lifecycle and tools as regular goals; they only change drafting/continuation wording and completion expectations.
29
- - **Full draft confirmation and creation output**: draft confirmation uses a plain-text report, and after confirmation the finalized objective is printed directly into the conversation.
30
- - **Full completion output**: completion prints a report directly into the conversation, including optional evidence and full goal details.
31
- - **Built-in question tools**: `goal_question` and `goal_questionnaire` provide package-local user-dialogue tools with `goal_` prefixes.
32
- - **Centralized tool names**: published tool names and allowlists live in `goal-tool-names.ts`.
33
- - **Questionnaire componentization**: normalization, answer formatting, proposal confirmation, and question-tool registration live in `goal-questionnaire.ts`.
34
- - **Widget module split**: the above-editor Goal Beacon and widget-style notification text live under `extensions/widgets/`.
35
- - **Record/prompt/storage split**: goal record normalization, prompt construction, and disk serialization now live in separate tested modules instead of the orchestration file.
36
-
37
- ## Current validation
38
-
39
- Run locally:
40
-
41
- ```bash
42
- npm test
43
- npm run check
44
- npm pack --dry-run
45
- ```
@@ -1,133 +0,0 @@
1
- import {
2
- formatDuration,
3
- formatTokenValue,
4
- statusLabel,
5
- truncateText,
6
- } from "./goal-core.ts";
7
- import {
8
- latestAuditorResultForGoal,
9
- latestEventsForGoal,
10
- reconstructGoalLedger,
11
- type GoalLedgerEvent,
12
- } from "./goal-ledger.ts";
13
- import { type GoalRecord } from "./goal-record.ts";
14
-
15
- export function buildGoalCompactSummary(goal: GoalRecord, events: GoalLedgerEvent[]): string {
16
- const lines: string[] = [];
17
- lines.push(`Goal ${goal.id} — ${statusLabel(goal)}`);
18
- lines.push(` Objective: ${truncateText(goal.objective, 200)}`);
19
- if (goal.usage.tokensUsed > 0) {
20
- lines.push(` Usage: ${formatTokenValue(goal.usage.tokensUsed)}`);
21
- }
22
- if (goal.usage.activeSeconds > 0) {
23
- lines.push(` Time: ${formatDuration(goal.usage.activeSeconds)}`);
24
- }
25
-
26
- const recent = latestEventsForGoal(events, goal.id, 5);
27
- if (recent.length > 0) {
28
- lines.push(" Recent events:");
29
- for (const event of recent) {
30
- switch (event.type) {
31
- case "goal_paused":
32
- lines.push(` - paused: ${event.reason}`);
33
- break;
34
- case "goal_resumed":
35
- lines.push(` - resumed: ${event.reason}`);
36
- break;
37
- case "goal_tweaked":
38
- lines.push(` - tweaked: ${event.changeSummary}`);
39
- break;
40
- case "completion_requested":
41
- lines.push(` - completion requested${event.summary ? `: ${truncateText(event.summary, 80)}` : ""}`);
42
- break;
43
- case "audit_result":
44
- lines.push(` - auditor ${event.verdict}${event.verdict === "disapproved" ? `: ${truncateText(event.report, 80)}` : ""}`);
45
- break;
46
- case "goal_completed":
47
- lines.push(" - completed");
48
- break;
49
- case "task_list_set":
50
- lines.push(` - task list set: ${event.taskCount} tasks${event.blockCompletion ? " (blocking)" : ""}`);
51
- break;
52
- case "task_complete":
53
- lines.push(` - task complete: ${event.taskId}${event.evidence ? ` — ${truncateText(event.evidence, 60)}` : ""}`);
54
- break;
55
- case "task_skipped":
56
- lines.push(` - task skipped: ${event.taskId} — ${truncateText(event.reason, 60)}`);
57
- break;
58
- case "goal_aborted":
59
- lines.push(` - aborted: ${event.reason}`);
60
- break;
61
- default:
62
- break;
63
- }
64
- }
65
- }
66
-
67
- const auditor = latestAuditorResultForGoal(events, goal.id);
68
- if (auditor && auditor.verdict === "disapproved") {
69
- lines.push(` Auditor rejection (latest): ${truncateText(auditor.report, 120)}`);
70
- }
71
-
72
- if (goal.pauseReason) {
73
- lines.push(` Pause reason: ${goal.pauseReason}`);
74
- }
75
- if (goal.pauseSuggestedAction) {
76
- lines.push(` Suggested action: ${goal.pauseSuggestedAction}`);
77
- }
78
-
79
- return lines.join("\n");
80
- }
81
-
82
- export function buildCompactionSummary(args: {
83
- goalsById: Map<string, GoalRecord>;
84
- focusedGoalId: string | null;
85
- ledgerEvents: GoalLedgerEvent[];
86
- capOpenGoals?: number;
87
- capEventsPerGoal?: number;
88
- }): string {
89
- const { goalsById, focusedGoalId, ledgerEvents, capOpenGoals = 20, capEventsPerGoal = 5 } = args;
90
-
91
- const lines: string[] = [];
92
- const openGoals = Array.from(goalsById.values()).filter((g) => g.status !== "complete");
93
- const reconstructed = reconstructGoalLedger(ledgerEvents);
94
-
95
- if (focusedGoalId && goalsById.has(focusedGoalId)) {
96
- const focused = goalsById.get(focusedGoalId)!;
97
- lines.push(`[FOCUSED GOAL]`);
98
- lines.push(buildGoalCompactSummary(focused, latestEventsForGoal(ledgerEvents, focusedGoalId, capEventsPerGoal)));
99
- lines.push("");
100
- }
101
-
102
- const otherOpen = openGoals.filter((g) => g.id !== focusedGoalId);
103
- if (otherOpen.length > 0) {
104
- lines.push(`[OTHER OPEN GOALS — ${otherOpen.length} total]`);
105
- for (const goal of otherOpen.slice(0, capOpenGoals)) {
106
- lines.push(`- ${goal.id} — ${statusLabel(goal)} — ${truncateText(goal.objective, 120)}`);
107
- }
108
- if (otherOpen.length > capOpenGoals) {
109
- lines.push(`... and ${otherOpen.length - capOpenGoals} more`);
110
- }
111
- lines.push("");
112
- }
113
-
114
- if (reconstructed.terminalGoals.size > 0) {
115
- lines.push(`[TERMINAL GOALS — ${reconstructed.terminalGoals.size} completed or aborted]`);
116
- for (const [goalId, state] of reconstructed.terminalGoals) {
117
- const label = state.latestStatus === "complete" ? "completed" : "aborted";
118
- lines.push(`- ${goalId} — ${label}${state.completedAt ? ` at ${state.completedAt}` : ""}${state.abortedAt ? ` at ${state.abortedAt}` : ""}`);
119
- }
120
- lines.push("");
121
- }
122
-
123
- if (openGoals.length === 0 && reconstructed.terminalGoals.size === 0) {
124
- lines.push("[NO GOALS]");
125
- lines.push("No open or terminal goals recorded in this session.");
126
- }
127
-
128
- lines.push("[INSTRUCTION]");
129
- lines.push("Continue from the focused goal above, or ask the user to run /goals, /goals-set, or /goal-focus.");
130
- lines.push("Do not rely on chat memory for goal state; use the facts above.");
131
-
132
- return lines.join("\n");
133
- }
@@ -1,77 +0,0 @@
1
- export interface GoalUsageLike {
2
- tokensUsed: number;
3
- activeSeconds: number;
4
- }
5
-
6
- export interface GoalDisplayRecordLike {
7
- objective: string;
8
- status: "active" | "paused" | "complete";
9
- autoContinue: boolean;
10
- usage: GoalUsageLike;
11
- sisyphus: boolean;
12
- stopReason?: "user" | "agent";
13
- }
14
-
15
- export { isQuestionLikeToolName } from "./goal-tool-names.ts";
16
-
17
-
18
- export function truncateText(value: string, max = 120): string {
19
- const oneLine = value.replace(/\s+/g, " ").trim();
20
- return oneLine.length > max ? `${oneLine.slice(0, max - 3)}...` : oneLine;
21
- }
22
-
23
- export function displayObjectiveTitle(objective: string): string {
24
- const lines = objective.replace(/\r/g, "").split("\n").map((line) => line.trim()).filter(Boolean);
25
- const sectionHeader = /^(success criteria|boundaries|constraints|steps|order rules|don'ts|if blocked|if blocked \/ unclear \/ failing|sisyphus reminder)\s*[::]/i;
26
- for (const line of lines) {
27
- if (/^=+\s*(?:sisyphus\s+)?goal\s*=+$/i.test(line)) continue;
28
- const objectiveMatch = line.match(/^(?:objective|目标)\s*[::]\s*(.+)$/i);
29
- if (objectiveMatch?.[1]) return objectiveMatch[1].trim();
30
- if (sectionHeader.test(line)) continue;
31
- return line;
32
- }
33
- return truncateText(objective);
34
- }
35
-
36
- export function formatTokenValue(value: number): string {
37
- const safe = Math.max(0, Math.floor(value));
38
- const compact =
39
- safe >= 1_000_000_000
40
- ? `${(safe / 1_000_000_000).toFixed(safe >= 10_000_000_000 ? 0 : 1).replace(/\.0$/, "")}B`
41
- : safe >= 1_000_000
42
- ? `${(safe / 1_000_000).toFixed(safe >= 10_000_000 ? 0 : 1).replace(/\.0$/, "")}M`
43
- : safe >= 10_000
44
- ? `${(safe / 1_000).toFixed(0)}K`
45
- : safe >= 1_000
46
- ? `${(safe / 1_000).toFixed(1).replace(/\.0$/, "")}K`
47
- : String(safe);
48
- const exact = safe.toLocaleString("en-US");
49
- if (compact === exact) return `${exact} tokens`;
50
- return `${compact} (${exact}) tokens`;
51
- }
52
-
53
- export function formatDuration(seconds: number): string {
54
- const total = Math.max(0, Math.floor(seconds));
55
- const hours = Math.floor(total / 3600);
56
- const minutes = Math.floor((total % 3600) / 60);
57
- const secs = total % 60;
58
- if (hours > 0) return `${hours}h${minutes.toString().padStart(2, "0")}m${secs.toString().padStart(2, "0")}s`;
59
- if (minutes > 0) return `${minutes}m${secs.toString().padStart(2, "0")}s`;
60
- return `${secs}s`;
61
- }
62
-
63
- export function statusLabel(goal: Pick<GoalDisplayRecordLike, "sisyphus" | "status" | "autoContinue" | "stopReason">): string {
64
- const prefix = goal.sisyphus ? "sisyphus " : "";
65
- if (goal.status === "active" && goal.autoContinue) return `${prefix}running`;
66
- if (goal.status === "paused" && goal.stopReason === "agent") return `${prefix}paused (agent)`;
67
- return `${prefix}${goal.status}`;
68
- }
69
-
70
- export function footerStatus(goal: GoalDisplayRecordLike): string {
71
- const usageBits: string[] = [];
72
- if (goal.usage.activeSeconds > 0) usageBits.push(formatDuration(goal.usage.activeSeconds));
73
- if (goal.usage.tokensUsed > 0) usageBits.push(formatTokenValue(goal.usage.tokensUsed).split(" ")[0]);
74
- const usage = usageBits.length > 0 ? ` [${usageBits.join(" ")}]` : "";
75
- const prefix = goal.sisyphus ? "goal✊" : "goal";
76
- return `${prefix}: ${statusLabel(goal)}${usage} - ${truncateText(goal.objective, 60)}`;
77
- }
@@ -1,263 +0,0 @@
1
- import type { GoalTask } from "./goal-record.ts";
2
-
3
- export type GoalDraftingFocus = "goal" | "sisyphus";
4
-
5
- export interface GoalConfirmationIntentLike {
6
- focus: GoalDraftingFocus;
7
- originalTopic: string;
8
- startedAt?: number;
9
- }
10
-
11
- export interface DraftProposalInput {
12
- intent: GoalConfirmationIntentLike | null;
13
- hasUnfinishedGoal: boolean;
14
- objective: string;
15
- sisyphus?: boolean;
16
- draftId?: string;
17
- }
18
-
19
- export type DraftProposalValidation =
20
- | { ok: true; objective: string; expectedSisyphus: boolean }
21
- | { ok: false; message: string; clearDrafting?: boolean };
22
-
23
- export type ToolGateDecision =
24
- | { block: false }
25
- | { block: true; reason: string };
26
-
27
- // ── Shared formatting helpers ──────────────────────────────────────────────
28
-
29
- function formatModeLabel(sisyphus: boolean): string {
30
- return sisyphus ? "Sisyphus (prompt/criteria style)" : "Normal goal";
31
- }
32
-
33
- function formatPrefixedLines(content: string): string[] {
34
- const lines: string[] = [];
35
- for (const rawLine of content.split("\n")) {
36
- const trimmed = rawLine.trim();
37
- if (!trimmed) continue;
38
- if (trimmed.startsWith("│")) {
39
- lines.push(rawLine);
40
- } else {
41
- lines.push(`│ ${rawLine}`);
42
- }
43
- }
44
- return lines;
45
- }
46
-
47
- function formatSection(title: string, content: string): string[] {
48
- const body = formatPrefixedLines(content);
49
- return ["", `─── ${title} ───`, "", ...body];
50
- }
51
-
52
- export function renderConfirmationTasks(tasks: GoalTask[], indent: number): string[] {
53
- const prefix = " ".repeat(indent);
54
- const lines: string[] = [];
55
- for (const t of tasks) {
56
- const lw = t.lightweightSubtasks ? " (lightweight)" : "";
57
- const contract = t.verificationContract ? ` contract: ${t.verificationContract}` : "";
58
- lines.push(`${prefix}[ ] ${t.id}: ${t.title}${lw}${contract}`);
59
- if (t.subtasks && t.subtasks.length > 0) {
60
- lines.push(...renderConfirmationTasks(t.subtasks, indent + 1));
61
- }
62
- }
63
- return lines;
64
- }
65
-
66
- export function promptSafeObjective(objective: string): string {
67
- return objective.replace(/<\/?untrusted_objective>/gi, (tag) => tag.replace(/</g, "&lt;").replace(/>/g, "&gt;"));
68
- }
69
-
70
- const VERIFICATION_CONTRACT_RE = /^Verification contract:\s*(.+)$/im;
71
-
72
- const CONVENTIONAL_SECTION_NAMES = [
73
- "success criteria",
74
- "boundaries",
75
- "constraints",
76
- "if blocked",
77
- "if blocked / unclear / failing",
78
- "don'ts",
79
- "sisyphus reminder",
80
- "objective",
81
- "目标",
82
- "ordered steps",
83
- "order rules",
84
- "steps",
85
- ];
86
-
87
- /**
88
- * Extract a `Verification contract:` section from a goal objective and return
89
- * the cleaned objective (without the contract section) and the contract text.
90
- *
91
- * The contract section is a single line matching:
92
- * Verification contract: <text>
93
- *
94
- * It can appear anywhere in the objective, but by convention it goes after
95
- * the other sections (like Success criteria, Boundaries, Constraints).
96
- *
97
- * If no contract section is found, `verificationContract` is undefined.
98
- */
99
- export function extractVerificationContract(objective: string): { objective: string; verificationContract?: string } {
100
- const lines = objective.replace(/\r/g, "").split("\n");
101
- let contract: string | undefined;
102
- const filtered: string[] = [];
103
-
104
- for (const line of lines) {
105
- const trimmed = line.trim();
106
- const m = VERIFICATION_CONTRACT_RE.exec(trimmed);
107
- if (m) {
108
- contract = m[1].trim();
109
- // Skip this line — don't add it to the cleaned objective
110
- } else {
111
- filtered.push(line);
112
- }
113
- }
114
-
115
- return {
116
- objective: filtered.join("\n"),
117
- verificationContract: contract || undefined,
118
- };
119
- }
120
-
121
- export function buildDraftConfirmationText(args: {
122
- focus: GoalDraftingFocus;
123
- originalTopic: string;
124
- objective: string;
125
- autoContinue: boolean;
126
- }): string {
127
- const lines: string[] = [];
128
- lines.push("● Goal draft ready for confirmation.");
129
- lines.push("");
130
- lines.push("─── Draft Details ───");
131
- lines.push(`│ Mode: ${formatModeLabel(args.focus === "sisyphus")}`);
132
- lines.push(`│ Auto-continue: ${args.autoContinue ? "yes" : "no"}`);
133
- lines.push(...formatSection("Original Topic", args.originalTopic.trim()));
134
- lines.push(...formatSection("Proposed Goal", args.objective));
135
- return lines.join("\n");
136
- }
137
-
138
- export function buildTweakConfirmationText(args: {
139
- currentObjective: string;
140
- newObjective: string;
141
- changeSummary: string;
142
- sisyphus: boolean;
143
- tasks?: GoalTask[];
144
- }): string {
145
- const lines: string[] = [];
146
- lines.push("● Goal tweak ready for confirmation.");
147
- lines.push("");
148
- lines.push("─── Draft Details ───");
149
- lines.push(`│ Mode: ${formatModeLabel(args.sisyphus)}`);
150
- lines.push(...formatSection("Change", args.changeSummary));
151
- lines.push(...formatSection("Current Objective", args.currentObjective));
152
- lines.push(...formatSection("Proposed New Objective", args.newObjective));
153
- if (args.tasks && args.tasks.length > 0) {
154
- const taskLines = renderConfirmationTasks(args.tasks, 0);
155
- lines.push("");
156
- lines.push(`┌─ TASKS ─────────────────────────────────────┐`);
157
- for (const tl of taskLines) lines.push(tl);
158
- lines.push(`└──────────────────────────────────────────────┘`);
159
- }
160
- return lines.join("\n");
161
- }
162
-
163
- export function evaluateDraftingToolGate(args: {
164
- toolName: string;
165
- draftingFocus?: GoalDraftingFocus | null;
166
- tweakDraftingGoalId?: string | null;
167
- activeGoalId?: string | null;
168
- proposeToolName?: string;
169
- tweakApplyToolName?: string;
170
- getGoalToolName?: string;
171
- }): ToolGateDecision {
172
- // Goal confirmation is prompt-guided, not runtime-enforced. The agent should
173
- // avoid substantive work before confirmation, but minimal reconnaissance is allowed.
174
- void args;
175
- return { block: false };
176
- }
177
-
178
- export function validateGoalDraftProposal(input: DraftProposalInput): DraftProposalValidation {
179
- if (input.intent === null) {
180
- return {
181
- ok: false,
182
- message: "propose_goal_draft REJECTED: no /goals or /sisyphus intent discussion is in progress. Tell the user to invoke /goals <topic> or /sisyphus <topic> first, or use /goals-set / /sisyphus-set for immediate creation.",
183
- };
184
- }
185
-
186
- const expectedSisyphus = input.intent.focus === "sisyphus";
187
- const actualSisyphus = input.sisyphus === true;
188
- if (actualSisyphus !== expectedSisyphus) {
189
- return {
190
- ok: false,
191
- message: `propose_goal_draft REJECTED (focus gate): confirmation focus is "${input.intent.focus}" (user invoked ${input.intent.focus === "sisyphus" ? "/sisyphus" : "/goals"}) but you passed sisyphus=${actualSisyphus}. Set sisyphus=${expectedSisyphus} to match the user's choice, then retry. Do NOT change the user's mode autonomously.`,
192
- };
193
- }
194
-
195
- const objective = input.objective.trim();
196
- if (!objective) {
197
- return { ok: false, message: "propose_goal_draft REJECTED: objective is empty." };
198
- }
199
-
200
- return { ok: true, objective, expectedSisyphus };
201
- }
202
-
203
- export function goalDraftingPrompt(topic: string, focus: GoalDraftingFocus): string {
204
- const safeTopic = promptSafeObjective(topic.trim() || "(no topic provided — ask the user what they want to accomplish)");
205
- const header = focus === "sisyphus"
206
- ? "[GOAL CONFIRMATION focus=sisyphus]\nThe user invoked Sisyphus intent discussion (/sisyphus). Help turn their request into a confirmed goal contract. Do NOT start substantive work yet."
207
- : "[GOAL CONFIRMATION focus=goal]\nThe user invoked goal intent discussion (/goals). Help turn their request into a confirmed goal contract. Do NOT start substantive work yet.";
208
-
209
- const commonProtocol = [
210
- "Confirmation protocol:",
211
- "- Treat this as a lightweight conversation with the user, not a separate long-running runtime phase.",
212
- "- If the topic is vague, ask one focused question with a recommended default. Use goal_question or goal_questionnaire when a structured answer would help, but plain conversation is acceptable.",
213
- "- Targeted read-only research is allowed when it helps define a better goal contract; do not start implementation before confirmation.",
214
- "- If the topic is already concrete, you may proceed directly to propose_goal_draft.",
215
- "- The goal contract should make the objective, success criteria, boundaries, constraints, and blocker rule explicit.",
216
- "- Keep grilling assumptions until the objective, success criteria, boundaries, constraints, and blocker rule are clear enough to confirm.",
217
- "- If the objective naturally decomposes into trackable milestones, you MUST include the task list in the `tasks` parameter of `propose_goal_draft` so the user can accept both goal and tasks in a single confirmation dialog. Do NOT propose the goal without tasks and then call `propose_task_list` separately.",
218
- "- For simple single-step goals, no task list is required. The `tasks` parameter can be omitted.",
219
- "- After goal creation, `propose_task_list` is still available for user-requested task additions or structural changes.",
220
- "- propose_goal_draft opens the user's Confirm / Continue Chatting dialog. Confirm creates and focuses the goal; Continue Chatting means keep refining through normal proposal cycles.",
221
- "- create_goal is not a shortcut. Direct create_goal calls are rejected so the user keeps explicit say in goal creation.",
222
- ];
223
-
224
- const goalFocusItems = [
225
- "For /goals, propose a normal goal in this shape when ready:",
226
- "=== Goal ===",
227
- "Objective: <one-sentence outcome>",
228
- "Success criteria: <observable evidence the goal is done>",
229
- "Boundaries: <in scope / out of scope>",
230
- "Constraints: <hard rules>",
231
- "Verification contract: <optional — what verification evidence is required before marking complete, e.g. 'Run npm test (0 failures), grep for remaining references, re-read requirements and confirm every item is addressed'>",
232
- "If blocked: <default = stop and ask the user>",
233
- "Call propose_goal_draft with sisyphus=false and autoContinue=true unless the user asked otherwise.",
234
- ];
235
-
236
- const sisyphusFocusItems = [
237
- "For /sisyphus, remember that Sisyphus is a prompt/criteria style, not a separate step-counter mechanism.",
238
- "Propose a Sisyphus goal in this shape when ready:",
239
- "=== Sisyphus Goal ===",
240
- "Objective: <one-sentence outcome>",
241
- "Success criteria: <observable evidence the whole ordered goal is done>",
242
- "Boundaries: <in scope / out of scope>",
243
- "Constraints: <hard rules, files not to touch, etc.>",
244
- "Verification contract: <optional — what verification evidence is required before marking complete>",
245
- "Ordered steps: <preserve the user's requested steps and ordering; do not add preflight or reconnaissance steps they did not ask for>",
246
- "If blocked / unclear / failing: <default = stop and ask the user>",
247
- "Sisyphus reminder: Work patiently and sequentially. No rushing, no unrequested preflight steps, no improvising around blockers.",
248
- "Call propose_goal_draft with sisyphus=true and autoContinue=true unless the user asked otherwise.",
249
- ];
250
-
251
- return [
252
- header,
253
- "",
254
- "Topic the user provided:",
255
- "<goal_topic>",
256
- safeTopic,
257
- "</goal_topic>",
258
- "",
259
- ...commonProtocol,
260
- "",
261
- ...(focus === "sisyphus" ? sisyphusFocusItems : goalFocusItems),
262
- ].join("\n");
263
- }