Install
Install with PiG
pig install npm:@timmyjl12/pi-goalInstall with Pi
pi install npm:@timmyjl12/pi-goalPackages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.
Pi manifest JSON
The pi field of package.json.
{
"extensions": [
"./index.ts"
]
}README
Written by the package's publisher, shown as published in version 0.1.3 (README.md). PiG does not review it.
@timmyjl12/pi-goal
Evidence-based persistent goals for the pi coding agent.
A goal records intent, acceptance criteria, evidence and audit separately from task status. Completion is gated on the goal's current definition, never on self-report: a checked-off todo list is not proof.
One command starts a goal and keeps working until it is provably complete:
/goal <goal> # start now, in the configured default mode (ships guided)
/goal cheap <goal> # start now, in cheap mode
/goal mode cheap # persist cheap as the default for later runs
Guided and cheap are the two user-facing names for the one completion policy of record, so there is no second setting to keep in sync:
| Mode | Reviewer model | Completion gate | Extra requirement |
|---|---|---|---|
| guided (default) | one tool-free call per review cycle, neuralwatt/deepseek-v4.1-flash-flex with max thinking | approved independent review plus current evidence | none |
| cheap | none — the extension makes no model call | fresh successful receipts from every attached configured check | at least one configured check |
Both modes still run the main agent's own model; that cost is separate from the Goal ledger. See Cheap and guided modes for the full contract, cost and assurance differences.
The package is independently loadable. It imports no sibling extension source and uses a project registry plus a branch-local session selection, not a process-global "current goal".
Load and optional installation
Published on npm as @timmyjl12/pi-goal. Nothing is activated until you load or install it. From the parent extensions directory, try the local entrypoint for one invocation:
pi --extension ".\pi-goal\index.ts"
Optional persistent local installation (writes personal Pi settings; run only if wanted):
pi install ".\pi-goal"
From npm, the corresponding command is pi install npm:@timmyjl12/pi-goal. For project-local installation, Pi supports --local; review project trust before loading executable extensions.
Do not enable an older @narumitw/pi-goal package concurrently. This package owns the goal tool and /goal command.
Node.js >= 22.19 is required. Verified against Pi SDK 1.5.2 on Node 26.10.0; earlier Pi hosts and the exact minimum Node release were not tested. Host packages (@earendil-works/pi-* and typebox) are peer dependencies supplied by pi.
Usage
The model-facing goal tool supports:
list, get, create, select, add_criterion, add_evidence, verify, review, apply, link_task, link_agent, pause, resume, complete.
One active goal, scoped to this project session
The registry may hold many goals, but exactly one can be active at a time, and that selection is scoped to the session and the project:
- The selection is a single value, not a set.
/goal <goal>,/goal use, the manager and the tool'sselectall replace it; nothing can add a second active goal./goal deleteis the only thing that clears it. - It is stored as a branch-local
pi-goal.activesession entry carryingsessionId. Entries written by another session are ignored, so two sessions in the same project cannot steer each other's goal, and branch navigation restores that branch's own selection. - Goals themselves live in the project's registry (
<cwd>/.pi/pi-goal/goals.json). A goal id from another project is not resolvable here, and an unresolved selection is reported as inactive rather than guessed. - There is deliberately no project-global active pointer. A new session in the same project starts unselected; re-select with
/goal use <goalId>.
Mutations require the exact active goalId and current expectedRevision. The original objective is an immutable required criterion. The tool cannot remove or weaken criteria, unlink work, change config, reset counters or submit a review verdict — and it cannot delete a goal: removal is user-only, through /goal delete.
In the TUI, /goal opens the Goal manager and /goal settings opens settings. Non-TUI /goal stays a text listing.
Text commands:
/goal <goal> # free text: create + select + enable the loop + start working (configured default mode)
/goal cheap <goal> # the same run in cheap mode (no reviewer model)
/goal guided <goal> # the same run in guided mode
/goal cheap|guided # switch the persisted default without creating a goal
/goal mode [cheap|guided] # show (or set) the effective mode, loop switches and reviewer model
/goal list
/goal show <goalId>
/goal create <title> :: <objective>
/goal use <goalId>
/goal pause|resume <goalId>
/goal complete <goalId>
/goal delete [goalId] # permanently remove ONE goal and its evidence (defaults to the active goal)
/goal verify <goalId> # confirmed one-shot dispatch; the goal tool runs checks
/goal review <goalId> # paid independent review OR free checks-only assessment
/goal settings # TUI settings, effective text config elsewhere
/goal apply <goalId> [actionId] # confirmed one-shot dispatch for pending actions
/goal help
Removing a goal
/goal delete [goalId] permanently removes exactly one goal from the project registry. Its definition, evidence, reviews and audit are removed with it, and there is no undo. With no argument it removes the currently active goal and clears the session selection; with a goal id it removes that goal and leaves the selection alone. An unknown id is reported and nothing is changed.
Deletion is deliberately narrow and user-initiated only:
- The
goaltool has nodeleteoperation, so the model can never remove a goal on its own. - There is no batch form; one command removes one record.
- Completed goals can be deleted too, since deleting is a decision about what you want to keep rather than a mutation of a goal's proof. When you only want to hide completed history and keep the proof, use the manager's archive instead.
Argument disambiguation
A first word is treated as a command only when the argument shape fits that command exactly. Anything longer is new goal text, so /goal list every TODO in src and /goal complete the parser refactor create goals instead of listing or completing the wrong record. Two documented structured verbs stay strict on purpose: /goal create <title> :: <objective> keeps its usage error, and /goal mode … is always the mode command. Both never silently start an unattended run. To make a goal whose text begins with a command word, use the free form without that word or /goal create <title> :: <objective>.
What /goal <goal> writes
A free-text run derives the title from the first sentence (bounded to 120 characters) and keeps the complete text as the immutable objective. It then writes the autonomy preset needed to actually keep going — without it a new goal is inert, because goal context injection and every continuation gate require enabled:
| Leaf | Value written |
|---|---|
enabled | true |
allowContinuation | true |
completionMode | the run's mode: independent-review (guided) or checks-only (cheap) |
supervisor.trigger | settled, unless you already chose tool_result |
supervisor.maxContinuationsPerSession | 50, only while it is still at the shipped 2 |
supervisor.cooldownMs | 0, only while it is still at the shipped 30000 |
The preset is written to the trusted project config (<cwd>/.pi/pi-goal/config.json), falling back to the global config in an untrusted project — never into an untrusted project. User choices are preserved: an already event-driven trigger is kept, and any continuation cap or cooldown you configured, tighter or looser, is left exactly as it is. Only the two shipped defaults are relaxed, for one reason each: 2 continuations cannot finish real work, and a continuation arriving inside the 30 s cooldown is dropped rather than delayed, which would end a run whose turns finish quickly. noProgressLimit, the call/token/cost/time budgets and the goal-tool gates still bound the run. allowTaskUpdates and allowAgentSteering are never turned on for you.
Cheap mode attaches every configured check to the new goal, because checks-only completion cannot succeed without one; with no checks configured it refuses instead of creating a goal that could never complete. Add a check in /goal settings → Checks first.
If the preset write fails, the goal is still created and selected but stays inert; the command says so and starts nothing. Repair the config in /goal settings, then send any message — the selected goal is picked up again.
Commands never execute configured checks or task/agent effects themselves. With an interactive confirmation they create a bounded one-shot request and send the main model an instruction to call the real goal tool with that request id. The request is shown as requested/running/passed|failed/cancelled/expired; merely sending the instruction is not success, and the no-invocation case expires visibly. Headless command use explains the exact tool call instead of pretending to run it. Direct goal-tool verify/review/apply works without the TUI.
Goal manager and settings
The overlay manages multiple goals and completed/archived history. It shows the full immutable objective, criteria, evidence/check proof, linked work and audit, with explicit refresh. User-only edits include title, additional criteria, check selection, link removal, archive metadata and budget reset; removing a reference never edits a task or stops a worker. A definition edit invalidates earlier review/proof.
Settings expose enablement, review model/provider/thinking/trigger, budgets/timeouts/cooldown, effect/continuation permissions, widget and configured checks. Values show effective provenance and draft state. Save explicitly targets global or trusted-project config; project overrides remain visible. Invalid config blocks execution instead of spending under guessed defaults. Model/provider are a pair; both null uses the current model.
Verify/review/apply still submit the original goal tool through normal permissions, after closing the overlay so native permission dialogs remain visible. A review state of reviewed means the independent call executed, not that it approved the goal. Model-facing tools cannot perform the user-only edits.
The extension owns only its goal status key and optional pi-goal widget, never the footer. These are cached render-only views; no file/provider/model calls happen in render. New runs receive a hidden, bounded pi-goal.context message when the selected goal definition changes. This is context, not completion evidence or an automatic extra model request.
Cheap and guided modes (and checks-only)
There is exactly one policy of record, the completionMode leaf. Four paths write it and they all write the same value:
| You type | Persists | Creates a goal |
|---|---|---|
/goal <goal> | the run's mode | yes |
/goal cheap <goal> / /goal guided <goal> | that mode | yes |
/goal mode cheap|guided, or bare /goal cheap|guided | that mode | no |
| Actions → Switch to … mode, Settings → General → Completion mode | that mode | no |
It ships as guided, and it is a persisted default: every run honours the stored value, including a bare /goal <goal>, so choosing cheap is durable until you change it back. It is also project-scoped, which means it gates completion for every open goal — switching to cheap makes each open goal check-gated, and switching back to guided makes them review-gated again. The effective value is shown by /goal mode and in the status line, which appends [checks-only].
Guided (independent-review, the default) spends one separate, tool-free reviewer-model call per review cycle, using neuralwatt/deepseek-v4.1-flash-flex with max thinking unless you change it. Cheap (checks-only) makes no reviewer-model call at all in the extension: continuation guidance is generated deterministically, and review becomes a read-only assessment rather than a paid inference. The main agent's own model still runs in both modes — that cost is not part of the Goal ledger.
To switch the persisted policy without creating a goal, run /goal mode cheap (or set it explicitly):
{
"completionMode": "checks-only"
}
Model preferences are retained for switching back, and switching modes does not reset counters or silently restart a stopped Goal. For bounded automatic guidance, the automation controls stay separate — mode selection alone never enables them. An explicit /goal <goal> run writes them for that run (see What /goal <goal> writes); to enable them by hand:
{
"completionMode": "checks-only",
"enabled": true,
"allowContinuation": true,
"supervisor": { "trigger": "settled" }
}
Attach at least one user-configured check to the Goal through the manager. Every required criterion must be covered by current successful check receipts; no checks, artifact-only coverage, stale/failed/denied/aborted receipts or unresolved linked work remain blocked. The model cannot create check commands, weaken criteria, change this mode or invent receipts.
Review becomes Assess checks, a read-only deterministic assessment—not independent approval. Verify still executes original configured tools through normal permissions. Completion uses the ordinary cancellable goal complete tool with current locked proof/policy validation. Automatic guidance asks the existing main agent to read the Goal's fresh revision and verify/complete; it never marks completion from an uncancellable settlement callback. Continuation caps, cooldown, recovery/input/UI ownership and no-progress bounds remain; main-agent tokens can be used when continuation is enabled.
/goal mode reports the effective mode, which config file supplies it (built-in default, global, or project), the loop switches and the actual binding limit. Bounds differ by mode: a cheap run has no reviewer calls to budget, so the continuation cap and noProgressLimit bind; a guided run spends one review call per cycle, so the smaller of supervisor.maxCallsPerSession and the continuation cap binds (with the shipped defaults that is 20, below the preset's 50). Both stop with a visible stoppedReason rather than looping.
A clean final agy response that strictly identifies an embedded pi://conversation.md payload as truncated before both the conversation history and current request arrived preserves the guided no-progress streak and previous progress fingerprint, so it cannot influence the next ordinary review's comparison. Those reviews still consume call, token, cost, and time budgets, so repeated transport failures stop at the configured outer limits rather than noProgressLimit. The check is deliberately narrow: other providers, generic truncation/refusal prose, thinking blocks, and ambiguous wording use ordinary no-progress accounting. This exemption does not repair transport, retry the provider, compact the session, or relax completion/evidence gates.
Checks-only never fabricates an approved model review or replays old independent task/steering proposals. Its completion history is explicitly labelled even after switching back. It offers less assurance: successful checks cannot establish untested semantics. Keep independent review for work needing that additional judgement. Return completionMode to independent-review to restore the default policy; switching modes does not reset counters or silently restart a stopped Goal.
Full goal data pages
get is a bounded summary by default. Request collection (criteria, evidence, linkedTasks, linkedAgents, audit, checks) with limit (1–100, default 10) and cursor for explicit pages. Follow dataPage.nextCursor directly; collection pages accept numeric or string offsets. Pages preserve criterion text and carry explicit owned-registry references for oversized raw records rather than silently implying complete data.
Storage
- Project registry:
<cwd>/.pi/pi-goal/goals.json(versioned, multiple goals). - Global config:
<agentDir>/pi-goal/config.json. - Trusted project config:
<cwd>/.pi/pi-goal/config.json. - Active selection: a branch-sensitive pi
customsession entry (pi-goal.active). It is restored only fromgetBranch()onsession_start/session_tree; there is no project-global active pointer.
Registry writes use a cross-process exclusive lock, an optimistic revision check and a unique-temp atomic rename with bounded Windows retry. A corrupt registry is reported with its original bytes retained; it is never reset silently. A foreign or stale lock is never deleted automatically.
Effective config is defaults < global < project, including per-check leaves. A project may override just a check timeout without copying its global command or input scope; later global changes still inherit. Known values are validated strictly, unknown keys are preserved on save, and only edited leaves are merged under the file lock. A new check must resolve a complete valid definition; missing fields are never invented. Invalid JSON is never overwritten with defaults.
Checks and evidence
Configured checks live only in config.json:
{
"checks": {
"typecheck": {
"tool": "powershell",
"command": "npm.cmd run typecheck",
"timeoutSeconds": 120,
"inputFiles": ["package.json", "tsconfig.json"]
}
}
}
tool is powershell (preferred on Windows) or bash. inputFiles is a nonempty explicit workspace-relative scope. The model can reference configured check IDs but cannot provide a command, arguments, timeout or input scope.
A successful check receipt is created internally only when all of these hold:
- the nested tool reports success, not a denial/error;
structuredContent.exit_codeis numeric and zero;- declared input hashes are unchanged before and after execution;
- the tool-call identity is present.
Receipts bind the goal definition revision, canonical workspace identity, effective check fingerprint, before/after input hashes, execution timing, tool call and output hash. Re-verification rehashes the same scope and current config. A same-ID config edit, a changed input, or a recaptured different artifact therefore invalidates old proof. Changes outside the declared scope cannot be detected and are an explicit verification limitation.
Artifact evidence is restricted to regular files inside the real workspace (traversal and realpath/symlink escape rejected), capped at 1 MiB, and stored as SHA-256 plus a bounded excerpt.
Optional integrations and limitations
reviewuses a separate, tool-free supervisor model request over a bounded goal/evidence/task/agent snapshot. The default isneuralwatt/deepseek-v4.1-flash-flexwithmaxthinking. Setenabled, model/provider overrides and limits explicitly; only explicitprovider: nullplusmodel: nulluses the current session model. Unknown, unauthenticated or out-of-scope configured models fail explicitly; they never silently fall back. A model without declared pricing is refused; only a catalogue model whose declared rates are all zero is treated as free. Manual goal-tool reviews return actual own nested-model usage to pi's native session accounting, including provider responses that fail validation. Background/late-cancelled review usage remains in the durable Goal ledger; that ledger is separate from main/child costs.- The supervisor reserves each call in the project registry before inference and
persists calls/tokens/cost/time/continuations/no-progress/action ids across reload.
The legacy
max*PerSessionconfig names mean per goal; reload never resets them. Output and request time are bounded (supervisor.requestTimeoutMs, default 120 s); an in-flight request can still cross a spend threshold, and main/child model cost is not included. Pending proposals are session-owned memory and are rejected after expiry/reload rather than silently replayed. applyaccepts only a bounded pending action id created by a validated review. It targets the current open active goal and a fresh snapshot, then calls the ORIGINALTaskCreate/TaskUpdate/steer_subagentthrough the caller'sctx.executeTool. Permission denials produce no applied state, create tasks are linked only after the owner acknowledges its stamped metadata, and a successful action invalidates the old review and stale sibling proposals. Each action id is deduplicated persistently.- Automatic review is off by default (
enabled: false, triggermanual). An explicit/goal <goal>run is the only thing that turns it on, and only in the config scope it writes: the trusted project config, or the global config in an untrusted project.settledandtool_resulttriggers are event-driven, coalesced and cooldown-bounded; they never poll tokens. At most one review is in flight per bound session. New user input, pause/select, branch navigation, abort or shutdown invalidates in-flight work and pending actions before awaited cleanup. - Automatic main-agent continuation is issued only through the native
agent_before_settleboundary, never fromagent_settled. It honours the existing continuation, pending messages/editor/UI, completed vs aborted/error outcome, canContinue, live linked work, persisted caps/cooldown and fallback recovery (pending,failurePending,continuationOwed, nonresponsive/legacy suppression). Fallback keeps continuation ownership; goal never clears fallback state or sends a competing prompt. link_task/link_agentresolve through the session-bound read-onlyGoalProviderClientover versionedpi.eventschannels (goal:tasks:*,goal:agents:*). Binding happens insession_startbut never emits or awaits discovery there; the firstresources_discover, command, tool orbefore_agent_startboundary kicks discovery, ready/changed hints only mark caches dirty, and every task/agent effect runs throughctx.executeToolinto the ORIGINAL owning tool (TaskUpdatelink,TaskCreatecreate,steer_subagentsteer) with agoalGuardthe owner validates after permission hooks. Linked work with no status provider blocks completion; missing/open/failed work is never guessed complete.- Numeric task ids are unique only inside the owning task store. A task link is
therefore keyed by
(providerId, scopeId, taskId); the durablescopeIdcomes from the owner's current snapshot and is captured in the same guarded call that stamps goal metadata. A provider revision is freshness, never identity: normal progress/reload keeps the link, while the same numeric id in another scope (new session store, recreated file, memory store) is a different work item. Same-scope progress needs no relink; a scope-less legacy link stays unresolved and is never inferred from the current session, so it must be relinked explicitly. Pre-T11 readers reject the addedscopeIdfield, so a source-only rollback after writing scoped links is not compatible; retain the records and disable/unload Goal or run a compatible build rather than stripping identity. - A known owner acknowledgement is delivery evidence even when the follow-up
snapshot is lost: accepted-but-unreconciled receipts keep the original
(providerId, scopeId, taskId)and action id and are never retried blindly or redirected into a rebound scope.GoalProviderClient.getTaskProviderCatalog()exposes bounded metadata-only provider/scope/writability views for planning; unscoped, truncated, ambiguous or missing sources are honestly read-only. - Foreign
tool_resultobservations (details.tasks/details.todosorstructuredContentarrays with recognizable ids/text/state) are bounded read-onlyobserved:<toolName>snapshots; tool-name presence alone never establishes state and provider-owned tool names are deduplicated. - Recovery arbitration (
src/recovery.ts,pi-fallback-chains:recovery:queryv1 withfailurePending/continuationOwed) yields while recovery is pending and suppresses goal continuation observably when a loaded fallback gives no usable reply; with no fallback loaded the native boundary gates decide. - In default independent-review mode,
goal completerefuses unless a current genuine review and all current proof exist. In explicit checks-only mode it requires fresh configured-check coverage instead, with a separate assurance label. Neither policy overrides unfinished, missing or wrong-scope linked work.
No automatic paid supervisor request is made by default (enabled: false, supervisor trigger manual).
Supervisor config sketch
{
"enabled": true,
"supervisor": {
"provider": "neuralwatt",
"model": "deepseek-v4.1-flash-flex",
"thinking": "max",
"trigger": "tool_result",
"requestTimeoutMs": 120000,
"cooldownMs": 30000,
"maxCallsPerSession": 20,
"maxTokensPerSession": 200000,
"maxCostUsdPerSession": 1,
"maxTimeMsPerSession": 600000,
"maxOutputTokens": 2048,
"maxActionsPerReview": 3,
"maxContinuationsPerSession": 2,
"noProgressLimit": 3
},
"allowTaskUpdates": false,
"allowAgentSteering": false,
"allowContinuation": false
}
Every field is represented in config.example.json. Task updates/steering/continuation
default to off; enabling them is explicit user configuration. Model-facing goal
operations cannot change config, reset budgets, weaken criteria or unlink work.
Async and resource behavior
- Evidence hashing uses sequential 64 KiB asynchronous reads, with a 1 MiB file cap plus one detection byte. Cancellation and read failures close the handle; only a bounded excerpt is retained.
- A proof pass shares at most 256 hash/size observations for repeated normalized paths. Large ledger scans yield to the event loop every 32 records, allowing UI/timers/cancellation to run even with cached digests. No file buffers or trust cache survive into later passes or the before/after phases of a configured check.
- Display refreshes coalesce to one running pass plus one latest pending context; rendering itself does no IO. Foreign-tool observations retain at most 32 recent read-only snapshots, with bounded rows and eviction diagnostics—not durable-data deletion.
- No worker pool, GPU job, polling loop or extra model request is introduced. Original tool permissions, request/continuation limits and proof revalidation remain intact.
This reduces avoidable work; it is not a hard machine-wide CPU/GPU/RAM/disk budget. External models and user-configured commands control their own resource use. Registry JSON parsing/serialization still scales with the complete ledger; very large registries need separate capacity planning. Local benchmark timings are development observations, not production guarantees.
Verification
npm.cmd --prefix .\pi-goal run check
npm.cmd --prefix .\pi-goal test -- --run test/providers.test.ts test/integration.test.ts test/goal-run.test.ts
test/goal-run.test.ts covers the /goal command contract: verb-versus-free-text
disambiguation, the cheap/guided presets and which configured values the preset is
allowed to relax, persisted-default inheritance through the real layered config loader,
the cheap-mode check prerequisite, and trust-scoped write targets. Its load-bearing
assertions were verified by reverting each fix and confirming the test fails.
Repository-only npm.cmd run test:e2e runs one /goal <goal> command on a real Pi session with scripted local models (no network): the run goes through a rejected review, more work, an approved review and goal complete, then stops by itself — alone, and with pi-todo, pi-fallback-chains, pi-subagents and pi-context loaded. A third case gives the agent no proof and checks that the run stops on the no-progress limit. node --experimental-strip-types test/goal-loop-e2e.ts live-reviewer <agentDir> is an opt-in, paid variant that sends the two reviews to the configured reviewer model.
Repository-only npm.cmd run test:smoke uses the real Pi loader/session in five hermetic cases: standalone, Goal before Todo, Todo before Goal, child isolation, and checks-only assessment without a reviewer provider. It asserts the SDK agent directory points into its owned temp sandbox before sibling loading, blocks inference, checks commands/core reads, and shuts down/disposes real sessions. Owned temp artifacts are retained for inspection rather than batch-deleted. No actual user config/tasks are loaded. Interactive TUI inspection and live paid-model review are not claimed by these checks.
Rollback / first enabled sessions
For a one-invocation trial, exit Pi and omit --extension next time. If explicitly installed persistently, remove that same source with pi remove ".\pi-goal" or disable it through pi config; do not delete Goal registries, evidence or Todo identity metadata. Turn off enabled in the selected config scope before investigating runaway calls, duplicate continuations, cross-session effects or unsupported completion. Keep other effects/continuation off until their behavior is observed.
Source rollback requires compatibility: scoped task links, sparse project check overrides, completion-mode settings and labelled checks-only completion records are not understood by older Goal readers. Switching back to independent review does not erase reduced-assurance history. Retain the records and use a compatible build or an explicit human-reviewed config conversion; never silently strip identities or replace unknown config with defaults. Supervisor spend labels are estimates, not a billing cap. Watch calls/cost, stop reasons, proof freshness and task conflicts during initial enabled use.
License
MIT. Original implementation; see LICENSE.