pi-continual-learning1.0.1
Continual learning for Pi at the harness and prompt surfaces — declarative tool-call guardrails plus memory retrieval, injection, and consolidation. Model weights are out of scope.
Untested on omp
This is a pi package. No one has reported whether it works on omp yet. If you try it, add your result below.
Reports 0
No reports yet.
Readme
pi-continual-learning
Learns durable Memory and scoped Harness rules from completed user tasks. Model weights are out of scope.
- Memory supplies a bounded metadata index before generation. Full entries are read only when needed; omitted entries remain discoverable.
- Harness uses one flat
ruleslist for new declarations:skillandtextdeliver scoped guidance, whilebashsupplies messages and optionally confirms or blocks a command before execution. Installed legacy policies retain their original protections through read-only compatibility. - AGENTS.md consolidation keeps common project instructions small and moves detailed knowledge into Memory or skill rules, retaining conditional pointers when needed.
These surfaces have different authority. Memory is durable, untrusted reference
knowledge supplied as escaped data in a run-start section; it cannot enforce behavior. Harness is the
executable-validation surface: a rule can guide, confirm, or block only through
the parent-owned evaluator and its evidence-backed positive/negative cases.
skill/text rules and AGENTS.md are guidance for a bounded context, not proof
that the model complied. Manual, built-in, personal, disabled, invalid, and
legacy protections remain human-owned. A task may produce proposals for more
than one surface, but the same statement is not copied merely to increase
coverage.
Install and commands
Python 3 must be available as python3 for the bundled Memory validator.
Pi 1.2 structured prompt sections are required for run-start Memory and Harness delivery.
Unsupported runtimes report an error instead of silently losing guidance under customPrompt.
pi install npm:pi-continual-learning
| Command | Purpose |
|---|---|
/learning |
The single user entry: open one menu, or pass an explicit request that the parent handles through the learn tool |
/learning (menu) |
Remember this request, learn from this task, maintain all knowledge, manage Harness rules, or inspect settings/history/undo |
/learning is the only documented user command. Planner children run with
--no-tools and a bounded inline dossier; the model sees one zero-argument
learn tool. Frozen research and recovery scripts keep internal
/memory- and /consolidate-shaped command bindings for provenance only;
those are not user entry points and are not offered in any menu or guidance.
Debug 模式
Debug 默认开启,独立于自动学习开关。用现有命令查看实际状态和目录,或持久修改开关;这些操作不调用模型:
/learning debug
/learning debug on
/learning debug off
开关是 <agent-dir>/continual-learning.json 的布尔字段 debug;省略等于 true,显式 false 关闭记录。命令合并配置并保留其他字段,损坏的配置不会被覆盖。Debug 配置无效时保留默认开启并显示诊断。已有 Pi 会话需 reload 后才加载新增记录器;之前的使用记录不会被补造。
日志只保存在私有 agent 根目录,默认位置如下。<project-hash> 是 canonical cwd 的完整 SHA-256,因此同名项目、路径别名和含空格的路径均有确定的归属。
~/.pi/agent/continual-learning/debug/<project-hash>/
<timestamp>-<pid>-<writer-uuid>-<segment>.jsonl
设置 PI_CODING_AGENT_DIR 时跟随该根目录。每个扩展实例使用独占文件;目录权限 0700,日志权限 0600;拒绝子目录 symlink、非普通文件、重复硬链接和已被替换的日志。分段上限 4 MiB,每条记录上限 64 KiB;轮换保留旧段,累计占用会随使用增长,清理时需显式选择自己的 debug 目录。
记录包含时间、PID、插件源码模块、事件/命令/工具入口、调用与父调用身份、projectId、session 文件与 ID、model、耗时、输入、实际返回值和错误 stack。每个根调用写一份 context:snapshot,冻结最近 12 条分支上下文;其余记录只带 contextRef 和必要身份,避免重复复制完整工具定义。toolsAdded 在快照里只保留名称、短描述和参数名摘要;长文本、深层结构、缺失上下文和缺失快照都有显式标记;context 与 data 使用独立投影预算。同一会话的多个 session_start / session_shutdown handler 合并成 lifecycle:batch,其中保留每个 handler 的 invocationId 和终态,失败单独记录;handlerCount 按身份数而非行数计(成功 handler 各占 started 与终态两行)。
除了 API 边界,UI 通知、工具激活、Harness 执行观测、Memory 投递观测、自动学习的 pending / skipped / run 开始与关闭、当前源码采集结果、learning history 的 mutation 终态,以及后台 pipeline 开始/关闭和未显示在 transcript 中的静默回执也有受控记录。回执保留原始 batch、worker ledger、phase 结果、Jev telemetry 和实际 artifact 路径;子进程源码采集和生成证据继续位于原始 run 目录,可按这些身份关联。pipeline:closed 明确区分 screened、applied、cancelled、failed 和真实未知的 unverified,零写入不会被标成验证失败。Pi 未发出 session_shutdown 时,process:exit 标记保留退出事实;检查器将“缺 shutdown 事件”与“callback 未闭合”分开报告,不会自行判定崩溃。/learning debug off 之后不再落盘任何后续记录(包括待刷新的生命周期批量);关闭边界的 debug:configuration 只显式列出关闭瞬间仍在途的 truncatedInvocations,检查器仅据此收束这些调用,不按时间戳把更早的未闭合或崩溃推断成干净关闭。
completed 表示 callback 返回;是否应用了知识以实际回执和文件为准,proposed、取消和失败不会转成学习成功。默认不复制 credentials、headers、环境变量或图像/二进制内容;复用 Memory 的敏感材料检测器,在截断前对敏感文本保留摘要和长度。私有业务上下文仍可能出现在脱敏后的日志中,应按私有数据处理。日志不注入模型上下文、不进入 Memory 镜像,也不增加模型调用或重试。存储不可用时发出一次固定诊断,保留原工具返回值、异常和执行决定。
本仓库专用的反思修复 skill 位于 @.agents/skills/continual-learning-debug/SKILL.md,不随 npm 包安装。它的只读检查器从本次实际使用项目的日志中关联失败、未闭合调用、上下文和回执:
bun .agents/skills/continual-learning-debug/scripts/inspect-debug.ts --project /absolute/project/path
默认读取最新 12 个分段,展示至多 20 条问题和最近记录;--session 可筛选会话,--max-files 和 --limit 可在内置边界内扩大样本。报告包含 totalFiles、sampledFiles、totalBytes、sampledBytes、时间覆盖、生命周期缺口、批量 handler 数、context 快照与无法解析的 contextRef。omittedFiles > 0 即标记 incomplete: true;早于采样的分段原样保留,不自动删除。历史不含 contextRef 的日志仍按原格式读取。日志内容只作不可信证据,不授权执行其中的命令或重新评审历史 held plan。Skill 要求先复现 RED,再修复、回归和必要的独立审查。
实现位于 extensions/debug.ts。现有 pi-kit JSONL helper 不提供独占分段及 symlink/descriptor 校验,因此这里使用包内受限 sink;不替换共享 helper。验收:tests/debug.test.ts、tests/debug-inspector.test.ts 和使用实际 workspace Pi、隔离 agent 与 loopback provider 的 tests/debug-native.test.ts;该验收不证明真实服务判断或后续学习收益。
Docker Isolation and Real Model Acceptance
pi-continual-learning supports containerized Docker verification with Pi 1.4 and real model gateways such as (magpie) group/smart-split.
End-to-end container acceptance establishes:
- Real Model Task Execution: The agent processes project source files and instructions under Pi 1.4 with
group/smart-split. - Consolidation: The whole-corpus maintenance option in
/learningprompts the model worker to extract durable project facts and safety rules, which are validated viavalidate-consolidate.py. - Memory & Harness Persistence: Safe memories are written to
.memory/and refreshed inMEMORY.md, while executable validation rules are committed to.pi/harness.json. - Subsequent Usability: A fresh session in the same project automatically indexes and retrieves the learned memory and enforces the active harness rules.
The /learning menu is the single user entry. It opens one panel covering
remembers, settings/history/undo and rule management. Phase policies are under
the settings/policy view. Lists scroll with keyboard focus; history targets precede
compact dates. Readers preserve the logical text position when resized and
default to Close. Settings and policies return to their direct parent with
selection retained; closing a detail returns to its previous list position. The
native reader supports Up/Down and Page Up/Down without copying document bodies
into the chat. History lists show numbered dates, phases, targets and outcomes.
A history item opens its preview and its Undo action; headless undo still
requires the exact id and --yes. Policy views show effective values and explain
that they control automatic phases; explicit consolidation uses validated plans
and still honors AGENTS.md disablement. Existing Memory retrieval continues when
automatic learning is off. RPC hosts retain native select dialogs.
An explicit request through /learning (or the learn tool) asks the parent to
retain the user's request. It can be used while automatic learning is off, and
the parent decides from the frozen evidence whether only Memory, only Harness,
or both apply. The request is evidence for a bounded proposal; validation,
privacy checks, mutation and the receipt remain parent-owned. A request can
correctly produce no write when it is not durable, safe, or sufficiently
grounded.
If review holds existing Memory and the repair returns no correction, the receipt
says Retained Memory review remains unresolved; no corrective operation was proposed. No files changed. The review remains incomplete; an empty response
does not prove that the records are correct or that protected intent changed.
Source evidence supporting the change is still required for a validated correction.
With Jev enabled, the parent can allow a semantic worker to decline an optional
new draft that has never been written. It checks the complete draft set against
user obligations, then checks the exact declined set and final remaining plan.
Both checks keep the original evidence and thresholds. Existing records and
required knowledge cannot use this path. The receipt says not learned and
counts no applied change for the draft. Original failures and costs remain.
An empty response, cancellation or uncertain review leaves the work pending.
Learning uses the current session model unless a separate provider/model pair
is configured. An explicit invalid or empty pair in continual-learning.json is diagnosed
and prevents a worker from silently using a different model; {} retains the
session-model default. The metadata index is deterministic and bounded; it does
not rank entries against each new request. The complete indexes remain available
for discovery when the injected list omits entries.
The rule-management option in /learning opens the Harness authoring
procedure. Project shared configuration remains the default authoring target;
personal and user-shared scopes require an explicit choice in the panel. A
missing target is a normal first-use state: a supported request creates one
complete validated configuration without an empty placeholder. Broad operational
safeguards can use scoped contextual guidance when no exact command gate is
established; guidance does not enforce a traffic rate limit. Essential unknowns
lead to an actionable clarification, not a missing-file dead end. Project tool
access uses the relative target path. Authoring activates a read-only
harness_preview tool: each changed enabled rule needs passing plain
positive/negative fixtures before the exact candidate can be written. A preview
is bound to predecessor bytes and consumed once; it never bypasses effective
configuration or native replacement authorization. Verification never requires
scratch files or a second write. The tool remains available for follow-up turns.
A new request replaces its scope; session changes, branch switches and shutdown
remove it. Every write still needs an exact, single-use preview. Pending
authoring does not block ordinary source writes or grant authority over another
Harness target.
An active authoring procedure also activates harness_write, a declared
one-step authoring tool. Its cases field is required in the tool schema, so
strict provider sampling advertises it; the parent validates the positive and
negative fixtures, the exact candidate and predecessor bytes, obtains
confirmation, writes atomically with readback, and records a learning receipt
plus an undoable history row. Cases are never persisted into rules. The tool is
inactive outside an authoring procedure and consumed on success. The two-step
harness_preview path above remains available; both paths keep their gates.
Internal frozen-provenance bindings
/learning is the only user command. Settings, phase policies, model choice,
history, undo, evaluation and backlog diagnostics are reached through the menu,
not through separate typed commands. Three internal slash-command bindings
(/memory, /consolidate, /harness) survive solely because frozen research
proofs drive /memory 整理记忆 and /consolidate backfill through a real
pi --print argv, and offline E2E drives /harness through its command handler.
They are never offered in any menu, never named by model guidance and never
documented as user input; see tests/continuous-command-proof.ts and
tests/live_harness_first_run.py.
Harness layers
Four user-owned layers, nearest wins:
- Project personal —
<project>/.pi/harness.local.json - Project shared —
<project>/.pi/harness.json - User, scoped to this project —
~/.pi/agent/harness/<scopeKey>.json - User, shared —
~/.pi/agent/harness.json
The scoped user layer reuses Memory's scope key, so a personal rule authored for
one project cannot silently govern another. It lives in a directory parallel to
memory/ and never inside a Memory root: a Memory root admits only regular
.md children, so a JSON configuration beside them fails consolidation's
privacy validation and aborts the run. The all-projects layer is kept, so a
genuinely cross-project rule still applies everywhere.
Harness rules
{
"rules": [
{
"id": "review-checklist",
"skill": "review",
"instructions": "For this review task, check the project's documented release constraints."
},
{
"id": "project-a-status",
"text": "Project A|A项目",
"instructions": "When discussing Project A, use its confirmed replacement plan."
},
{
"id": "confirm-publish",
"bash": "\\bpnpm\\s+publish\\b",
"action": "confirm",
"message": "Confirm the package, version, and registry before publishing."
}
]
}
review above is an example registered skill name, not a bundled skill. Use an
exact skill name available in the current session. Every rule has a stable id
and exactly one selector:
| Selector | Payload | Meaning |
|---|---|---|
skill |
instructions |
Guidance for that expanded /skill:<name> task |
text |
instructions |
Guidance for subjects matching a regex in retained conversation |
bash |
message, optional action |
Message with the real command result, or confirm / block before execution |
Omit action to allow a Bash call and append its message to the real result.
Empty strings, null, and observe are not actions. A block wins over confirmation;
multiple confirmation reasons produce one prompt. Missing UI, rejection, and
confirmation timeout leave the call unexecuted. Regex patterns inspect command
text, not an interpreted shell execution tree; verify both intended and unrelated
cases. Tests that might cause side effects use evaluator fixtures, not live commands.
Configuration and ownership
User-owned layers, nearest last:
<agent-dir>/harness.json— user shared.<agent-dir>/harness/<scopeKey>.json— user instructions scoped to the canonical project.<project>/.pi/harness.json— project shared and default authoring target.<project>/.pi/harness.local.json— explicit personal choice.
<agent-dir> defaults to ~/.pi/agent and honors PI_CODING_AGENT_DIR.
There is no global harness.local.json or project .pi/agent/harness*.json layer.
A personal filename is not a guarantee of Git exclusion; check ignore settings.
Package defaults are the outermost layer.
The nearest declaration of an id replaces the whole rule. Different identities
remain independent. { "id": "example", "enabled": false } disables an inherited
identity; a complete nearer definition can re-enable it. Invalid winning rules
are diagnosed rather than replaced with an outer same-id rule. An unreadable or
malformed layer is marked incomplete; any retained parse snapshot is labelled
stale, never verified as the current file.
Authoring reads the exact supplied file, assesses whether the request can be
represented, and writes a complete valid candidate once. Unsupported or ambiguous
requests leave files unchanged. Recommending AGENTS.md as a better home does not
authorize editing it. Existing invalid data requires an explicit native confirmation
preview before replacement; headless repair fails closed. If several layers need
repair, a strictly valid, approved target can be repaired independently while
unchanged other layers still have diagnostics. Activation remains incomplete and
Bash stays fail-closed where coverage is incomplete until those layers are fixed.
Approval binds the exact tool arguments and predecessor bytes across the entire
call, including any later policy confirmation. Target and other-layer raw bytes
are rechecked after the final asynchronous approval; changes require fresh
validation even when resolved diagnostics are identical. Execution policy is
resolved after asynchronous preflight and repair checks, so newly installed
protections govern the call. Recovery bypasses only incomplete coverage, never a
valid policy protecting configuration reads or writes.
The native write gate validates the whole candidate; edit is blocked for
Harness targets. This is not an OS sandbox or an interceptor for arbitrary shell writes.
Automatic learning writes only project-shared configuration. Evidence and
positive/negative evaluator cases are required. New identities cannot collide
with other layers, disabled declarations, invalid declarations, or manual rules.
learnedRules is parent-owned provenance binding each learned identity to its
current revision; a manual edit invalidates automatic ownership. Updates cannot
change the selector, re-enable a rule, or weaken its Bash action outside the reviewed correction contract.
Guidance scope and delivery
A skill read is not an invocation. Skill guidance names the applicable skill task in model-visible text. Text guidance names its matching condition and does not turn a historical mention into permission to apply it to unrelated work.
At before_agent_start, text matching scans the current prompt plus retained
branch conversation: user and assistant text, visible tool results and string
arguments, and retained summaries. Thinking, metadata, excluded shell output,
abandoned history, and Harness's own messages are not matching sources. Identified
configuration definitions are excluded; failed reads, native write outcomes,
mixed commands and ambiguous tool-call identities remain visible to matching.
Guidance contributes an additive structured section at before_agent_start.
It never returns a custom injection message or replaces the complete system prompt.
Non-context branch entries record scoped delivery revisions and sources. Unchanged
text guidance adds no duplicate row or ledger entry, while each matching run
still receives its structured section. A historical delivery alone does not
re-inject guidance after its ordinary matching text leaves the context.
An incomplete scan or configuration read retains complete prior scoped guidance from those entries.
The parent validates the saved scope header before delivery.
Unscoped historical guidance remains in history, with an explicit notice; it is not delivered.
Removed or changed rules retire through the same ledger; original history remains unchanged.
Legacy skill guidance uses this additive surface with the same skill-task boundary as flat guidance.
Saved configuration and execution gates remain unchanged.
Guidance delivery does not prove model compliance.
Bash evaluation also records non-context harness-behavior-observation session
entries. A decision binds its session, parent entry, input digest and exact
canonical rule revisions. Rule IDs, call IDs, commands and results are represented
by digests in these entries. At most 128 rules are listed; omitted rules, legacy
configuration or incomplete reads mark revision coverage incomplete. A matching
native completion links to the decision. The input digest covers this guardrail
stage; later extensions can still change arguments. Valid Pi timing proves that the handler
was invoked; it does not prove shell success or task correctness. Missing timing,
ambiguous or reused call IDs, changed sessions and exhausted tracking bounds
cannot establish execution. Observation failures do not change execution policy.
A confirmation from a closed or changed session cannot authorize an old call.
These records retain taskOutcome: unverified and effect: cannot-attribute.
They do not yet establish Memory consumption or paired task improvement.
Known limits: keywords first introduced by tools in the same run are picked up at the next agent start. Synchronous regex evaluation has volume limits, not preemptive cancellation of a single pathological pattern. Avoid unbounded patterns. Configuration readback proves persistence only; report effective activation, actual trigger verification, and unverified behavior separately.
Transcript display
/learning is the single user-facing entry: it opens one menu, or accepts an
explicit request that the parent handles through the learn tool. Its
rule-management option opens the same guarded Harness procedure directly,
owning exact candidate bytes, fixture validation and the native confirmation.
No advanced command form is offered to users; internal frozen-protocol
bindings remain for research and recovery scripts only. Each run shows two transcript rows: one
[learning] started · <subject> line and one final [learning] outcome line.
While a run is active, one spinner activity row sits above the editor (the
same live widget language as subagents): its identity names the agent
learner, while the bounded run topic is the row's activity. It is cleared
when the run ends, is cancelled or fails. The final row collapses
to one outcome line; when the run applied safe Memory, expanding it shows each
entry's description and body as Markdown. Frontmatter, filenames and receipt
metadata (usage, cost, source, calls, per-phase attempts and diagnostics) are
not displayed in either state — the receipt stays in the stored message's
model context. Private and credential-shaped entries are never shown. A run
with no applied safe Memory stays one unexpandable line. Errors and safety holds remain warning/error notices. Learning receipts retain failed/rejected/cancelled phases
beside applied changes, so a partial success never appears as an unqualified
success. Each learning batch retains its receipt under
runs/<project-scope>/receipts/<batch-id>/. The flat
learning-pipeline-receipt.json is the latest-result compatibility view.
Later learning does not replace earlier batches. Cancellation updates the same
batch's terminal receipt. Cost collection deduplicates equal batch views and
rejects conflicting views; missing historical usage stays unknown.
Harness authoring starts with one [harness] started · <request> inline
procedure row; the full procedure stays in model context. Failed and incomplete
events use error and warning tones. Expanded policy rows keep the policy,
action, outcome, tool, source and file; check rows keep their phase, policy and
artifact path. Reasons already shown in the title and check statuses already
shown in its label are not repeated as fields. Guidance rows likewise carry the
[harness] tag and show the skill or rule as their title subject, with source,
file and the complete prompt below, including prompts longer than 50 lines.
Clipped titles wrap when expanded. This display-only cleanup does not change
enforcement, guidance delivery or stored event data.
Existing configuration and safe upgrades
Installed policies, disabled, and skillPrompts remain supported runtime
input through a read-only compatibility boundary. A compatible old format is
reported as a notice, not unavailable configuration. In particular, a valid
write/edit-only policy does not block unrelated Bash commands after an upgrade.
Loading preserves every configuration byte. Existing cumulative disabled names
retain their historical same-ID effect, including saved flat rules, so upgrading
does not reactivate paused protections. Legacy same-name overrides of equivalent
built-in policies also keep their prior meaning.
New authoring and learning still produce flat rules. Adding them preserves
existing containers and provenance. Removing installed protections requires an
explicit before/after preview and authorization; old manual or learned entries
do not become automatically owned flat rules. No automatic migration is performed.
Legacy output/artifact checks, tool-argument paths and require gates retain
their original behavior. Legacy skill guidance retains its exact registered
invocation, optional user-message matcher, and configured system/user target.
These are compatibility capabilities, not new flat selectors. Mixed rules must
not bypass a matching block or create redundant approval prompts. Invalid
policies restrict only their identifiable tool/phase scope; unknowable scope or
unreadable configuration is conservatively diagnosed.
Built-in protection for futile interactive authentication and bulk Memory deletion
remains. A weaker Bash/text rule is never presented as an equivalent replacement
for an installed file or artifact policy. See the upgrade decision in
docs/adr/0005-preserve-installed-harness-protections.md in the source repository.
The deletion gate is path-scoped, not a blanket ban. It blocks generated shell
commands that delete either Memory folder or anything inside it. Deleting an
ordinary file outside those folders — including a retired memory.json, a
.memoryrc, or unrelated scratch cleanup — is unaffected. Deleting a Memory
entry is also supported, but only inside the parent-owned /consolidate
transaction: a delete needs an explicit CONTRADICTED, SUPERSEDED or
SUBSUMED verdict plus a non-empty preservedIn pointing at an existing file
or a rewrite in the same plan, with preservation, privacy, rollback and receipts
verified (extensions/incremental-memory-plan.ts).
Learning pipeline
All user-level configuration lives in one file,
<agent-dir>/continual-learning.json: the learning model, the two learning
triggers, phase policies, AGENTS.md budget, Jev, and the capability flags.
Both triggers are disabled by default: autoSettledLearning runs the
settled-task learner after a user task settles, and autoContinualLearning
exposes the parent learn tool so the agent can request
current-task Memory learning once before its final answer. The retired
autoMemory field is ignored. Both triggers share the automaticPhases
Memory policy: apply writes validated changes, propose saves them for
review, and off refuses to run.
maxNewMemoriesPerRun caps how many new Memory files one automatic task
may create (default 2, valid 1..16); rewrites and deletes of existing
records do not consume it, and an explicit /memory request is exempt. When a
fully reviewed automatic plan exceeds the cap, the parent saves the grounded
plan as a proposal, reports the exact count and limit, and writes no Memory
file or applied mutation receipt. Invalid values fail the configuration closed.
{
"model": "cliproxyapi/gpt-6-luna",
"autoSettledLearning": true,
"autoContinualLearning": true,
"automaticPhases": { "memory": "apply", "harness": "apply", "agents": "apply" },
"agentsMd": { "budgetBytes": 16384 },
"maxNewMemoriesPerRun": 2,
"jev": { "scopes": ["memory"] }
}
The model and settings options in /learning merge their fields into that
file and preserve every other section. The retired <agent-dir>/memory.json
pair and <agent-dir>/memory/settings.json learning fields are neither read
nor written; they are dead files and can be deleted.
All Memory is reviewable by default, including private (harness only)
entries: there is no authorization prompt, no per-run consent and no
allowPrivateMemory setting anywhere in the runtime. The retired key is not a
valid configuration field (an older file containing it is diagnosed as
invalid). Enabling a Jev scope means both shared and private bodies may be sent
to the external reviewer.
The metadata-only selector runs with --thinking off by default (an explicit
plannerThinkingLevel overrides it) so its output budget reaches the JSON
decision. If a selector worker still returns no decision, the parent records a
bounded parent-routed minimal selection diagnostic, selects no existing
entry and requests no phase from the model, then lets its own evidence screen
decide routing; the validated pipeline still runs. A nonempty but undecidable
selector response remains a reported failure, never a silent success. An agent
tool result reports a failure in any phase instead of only the last Memory
attempt.
Review workers may return their single JSON decision inside a single fenced JSON code block. The parent accepts exactly one complete fence around response for both coverage and body reviews; trailing prose, an inner fence or a second object stays rejected. Response digests still bind the original text.
An explicit organize request with no new durable knowledge completes inside
the parent. The parent verifies mirror drift, rebuilds both indexes and removes
empty learning scope directories; it starts no selector, planner or review
worker, writes no proposal and leaves nothing for an external actor to do. The
tool result says the organization is complete and the receipt records
organized-in-process as a routing decision. When the frozen task does contain
user-stated durable knowledge, the same tool still runs the validated learning
pipeline and can really write Memory and Harness changes. Credential-shaped
evidence and an invalid learning model keep their fail-closed paths; the
in-process branch never bypasses them.
The receipt separates evidence from routing. screen.reasons describes only
the frozen current-task slice, while screen.routing names policies and
explicit requests that enable or disable a phase regardless of that evidence.
A phase turned off by policy is not described as "no evidence". input.entryCount
is the size of the session or replay input; input.screenedEntryCount is the
number of frozen entries the evidence screen actually examined. A proposed
attempt with zero operations is not reported as a proposal saved for review.
An agent-requested run does not depend on the replay backlog: a malformed
history, a full queue, an already-acknowledged task reference or a session with
no persisted file still runs the validated Memory pipeline. Only a verified
reference binds the receipt for /consolidate backfill; otherwise the tool
result explicitly says no replay reference exists while reporting the real
learning outcome.
Planner children run without extensions, so the learning model must resolve from
the static model catalog or the user's custom-provider config. Before any worker
spawns, the parent resolves the configured or session model the same way a
no-extensions child would; a model registered by a session extension (for example
a proxy or routing extension) blocks learning immediately with the fix (choose a static-catalog model in
the /learning settings), instead of failing the selector mid-pipeline. An unavailable
preflight does not block: the selector's own diagnostic still reports it.
With autoSettledLearning enabled, agent_settled runs a deterministic
zero-token evidence screen after queued continuations and retries finish.
The fallback selector chooses integer positions from a parent-frozen metadata
index and explicit phase flags. The parent resolves exact filenames and binds the
task digest; the worker does not transcribe artifact identity. Invalid positions,
duplicates, mixed identity fields and missing decisions fail closed. Existing
selection artifacts retain their original identity and validation contract.
These decisions select review inputs; they do not authorize mutations.
Routine tasks launch no learning model. A metadata-only selector chooses the minimum sufficient existing Memory and relevant phases for the current Task Slice. Selected bodies and task evidence form one authoritative Learning Dossier. Only explicit full maintenance explores the whole corpus. After a complete ordinary task successfully edits or writes project source, automatic Memory learning first collects fresh source within the existing read-only scope. Original task observations remain intact. This extra collector call and its failures appear in the receipt; a source read is not itself a learned change. Existing citation, privacy, source-revision and semantic checks still control every write.
For observed TypeScript declaration files, generation also receives a bounded syntax view that locates direct function return types and their local declared members. It uses the bundled parser without reading extra files or resolving imports. The original evidence stays intact. These locations describe observed syntax, not runtime behavior or accepted knowledge; the model still selects the Memory content and every existing validation gate still applies.
New incremental project Memory also retains an exact observed-source block when a text unit uses a citation that selects one eligible complete outer function declaration. This applies only to successfully observed TypeScript declaration files. It preserves the selected declaration's parameters as well as its return type, without expanding the citation or inferring runtime behavior. Existing source units are not repeated. The added blocks count toward the original unit and body limits and receive the complete source, privacy and semantic review. They record an observation, including when cited as older or contrary evidence; they do not establish current truth. Existing entries, legacy formats and semantic corrections keep their contracts. Unsupported syntax, oversized views and unproved source occurrences do not qualify.
For new project API knowledge, the parent also checks a narrowly proved source relationship. A selected JavaScript wrapper call, its declaration and an observed package export map must identify one local factory, named return type and direct member. The original user's request must name the wrapper and member in one visible sentence. Within a single source-cited knowledge unit, the related statements may span sentences; separate units and descriptions are not combined. Missing role citations go to the existing single structural correction; the model must explicitly select and use them. For a draft rejected because roles are missing, the parent retains that obligation through correction, so dropping a trigger citation cannot erase it. Validated obligations remain bound to the same run and snapshot through admitted atomic project BODY correction, including exact-selected existing project rewrites. An initiating wrapper declaration already explicitly selected, used and validated by the same AST proof remains a separate source witness through structural and semantic correction; it is not a fourth ownership role or an added reference. Legacy proofs without that witness retain their original three roles. Both paths copy selected source bytes and neutral declaration relations while preserving model text, catalog entries and the prior frontmatter. Under the unique local direct-owner AST proof, a selected complete factory signature can witness both its factory and named owner roles; the direct member still needs its selected source span. Generic, imported, indirect, inherited, merged or overloaded owners do not gain this alternative. The original owner-heading selection remains valid. This does not infer runtime behavior, add unselected evidence or bypass any source, privacy, preservation or semantic check. Legacy formats retain compatibility.
Fresh project generation uses only knowledge with cited text units and one
source catalog. It does not ask the model to repeat factory/owner/member objects.
The existing source-relationship check proves complete roles from original
catalog citations already selected and used by text units, then retains only
that observed syntax through the same bounded source materializer. It adds no
missing role or unselected reference and preserves every original text/catalog
entry. Correct older atomic relation inputs remain readable.
Before current-file reads, snapshot-only validation collects metadata, catalog
and unit counts, quote bounds and missing source roles into the existing single
structural correction. The parent retains bound closure obligations across that
correction. Description errors identify the exact 400 UTF-16 code-unit limit;
JSON Schema's character bounds do not replace the parent check. Source, privacy,
current-file binding and complete semantic validation remain mandatory.
Already materialized, legacy and semantic-correction formats keep their contracts.
An empty Memory index plus explicit human facts or preferences lets automatic
learning route its already evidenced phases locally, without a selector model
call. An initial explicit request through /learning likewise goes straight to
Memory planning. The receipt marks this parent routing; planners and all
validation still run. Nonempty indexes and ambiguous inputs retain the metadata
selector, and ordinary maintenance retains its reviewed routing.
With Jev enabled, normal parent Memory application requires a separate knowledge
coverage review. New parent-selected question contract 2 separates each record's
own completeness criteria from the unchanged whole-plan criteria. A local pass
cannot override a missing global goal. Historical feedback keeps its exact
original questions; a changed contract invalidates its binding. A coverage request
without the complete cited review path is rejected before transport.
It checks the complete plan, including an empty plan, every
actual record and each named missing condition from the current or rejected
version. Original source text is not a stored Memory location. Removed or
replaced records cannot act as retained witnesses. Optional automatic nominations
do not become mandatory storage goals.
The coverage scores join the existing source, permission, preservation and
consistency requirements at the original thresholds. A missing SDK, unavailable
response or malformed proof cannot satisfy this required stage. A supported but
incomplete body can use the existing bounded repair slot; its corrected actual
plan receives every full review again. Each numeric decision and exact plan
binding remains in the private run artifacts. These mechanisms do not establish
that a model learned correctly or improved a later task.
A complete, safe, retained coverage response can still fail account binding.
That response stays invalid. The parent can continue its independent source and
body checks once. Only an actual hold from those checks can use the existing
single plan repair. A bad account alone cannot retry or write. A corrected plan
still needs every fresh review. The parent saves the original source diagnostic
and rejected-response binding without creating a coverage proof.
A proof for a complete plan cannot authorize a changed subset. The new coverage
protocol holds such partial application until an exact subset obligation proof
exists. Explicitly bounded historical studies retain their original independent
subset protocol and wire format. Held work remains pending and cannot start
later Harness or AGENTS phases.
Full maintenance also extracts grounded new knowledge when the Memory corpus is
empty. If the current session has no user or tool evidence, the parent may freeze one recent session
for the same canonical project (within seven days, at most 12 candidates and
8 MiB per source). Pi's active context projection excludes removed evidence;
older SDKs decline sources containing context edits. The receipt identifies the
source session and SHA-256 digest. This does not replay the backlog or change
automatic/incremental learning's current-task scope. With no usable evidence or
existing Memory, full maintenance makes zero model calls and reports
no learning input; use an explicit request through /learning to supply knowledge directly.
Package-owned prompts/*.md protocols are bound through typed builders. Planners
are read-only, have resource discovery disabled, and return bounded deltas or a
no-op. The parent owns identity, evidence, privacy, path and source-hash checks,
mutation, rollback, indexes, and receipts. An assistant's success claim is not a
receipt. Harness and AGENTS planning can overlap after the Memory gate; mutation
remains sequential. Saving a semantically held Memory proposal, including a partial
application with pending records, does not unlock those later planners. A fully
reviewed repair or an intentional validated proposal policy can pass the gate.
A later phase failure does not undo an earlier verified phase.
Real user tasks are coalesced while learning runs; extension continuations do not train themselves. Print/JSON sessions await completion and receipts. Turning settled learning off stops learning without disabling Memory retrieval. Receipts count every selector/planner attempt, applied operations, duration, input/output tokens, cache reads/writes, and provider cost availability. Selector failures also retain a parent-generated diagnostic in the attempt; raw model output and worker stderr are not copied into that diagnostic. A rejected selector response is retained separately in its private run directory, bounded to 64,000 characters with the frozen context digest and a truncation flag.
An explicit /consolidate always reaches selection, including tasks without
automatic-screen keywords. Explicit continuation prompts retain the original
request and its evidence. Task slices preserve complete human and tool entries
within their byte budget, report omitted entries, and reject an oversized original request rather
than clipping evidence. Assistant context retains visible text and tool calls,
while excluding reasoning, signatures, and provider transport metadata.
A failed tool invocation followed by a successful check
is eligible for Memory review; the planner still must justify a durable lesson,
and a reviewed selector verdict is not overridden by that recovery alone. Harness evidence means Harness-owned transcript evidence: guardrail event
entries, Harness guidance delivery, and the notes Harness attaches to tool
results. Repository text that merely mentions policies or harness files is not
evidence, so it starts no planner.
The zero-token screen is an opportunity filter, not a completeness claim. It
can miss a lesson; when it starts no pipeline, the parent may store a bounded
backlog reference to the settled session slice. Failed learning also stays pending.
/consolidate backfill retries up to three eligible, source-verified references;
auto-learning can recover one eligible reference after a normal attempt. It never
repeats task tools. Individual acknowledgments preserve failed siblings, project
leases prevent duplicate concurrent learning, and attempt ledgers retain failures
and known usage. Automatic retries stop after three attempts with backoff; explicit
backfill still has a finite attempt cap. Missing or changed source stays unresolved.
An interrupted provider call without returned usage has unknown cost, not zero cost.
For new coverage-reviewed rejections, backfill retains the exact historical
questions, every occurrence, and the original answer distributions. The original
receipt binds each private review artifact to its run, source, plan and bodies.
Changed, missing, ambiguous, unsafe or oversized diagnostics stop replay. Legacy
rejections without these fields keep their existing behavior. These diagnostics
are questions to investigate, not source facts, required answers or write approval.
Current source collection and every fresh review remain required.
Pi 1.2 can remove an empty assistant error during retry. Exact replay accepts
only this content-free null removal, strips the removed error metadata, and keeps
the original source hash, task digest and evidence positions. Meaningful
redactions remain refused. Replay eligibility does not clear the original task
failure or authorize a Memory or Harness change.
A latest phase with pending candidates cannot acknowledge its task as learned,
even if other candidates applied or that phase returned noop. Summaries warn and
show the latest unresolved count; a later completed phase supersedes its earlier
pending disposition. Source-verified backfill with an empty index uses the same
parent routing for explicit durable evidence as automatic learning, preserving all
mutation validation and semantic review.
Fresh tasks receive a compact index of deduplicated Memory filenames and
one-line descriptions. An unchanged index stays in place across user turns;
changed indexes replace stale references and missing context restores discovery.
Entry bodies are read on demand, never automatically injected. Metadata exposure
is not proof of use or benefit; current evidence and instructions take precedence.
Use the native read tool to consult relevant entries. Automatic correction revisits Memory actually read through unique successful read calls; failed or ambiguous reads do not nominate entries. Revisit is not factual evidence or permission to mutate. An explicit request through /learning retains its selected maintenance scope.
Local non-context memory-use-observation entries distinguish section preparation
from a complete body result. Complete file revisions come from the existing
bounded loader's raw bytes only when UTF-8 decoding round-trips exactly. At task
settlement, a full-body observation requires matching native handler timing and
content, a start-time session binding, one retained call/result pair, and an intact
branch back to preparation. Equal bodies in multiple snapshots remain ambiguous.
Partial, changed, failed, duplicate or foreign results establish no complete read.
Only hashes and native entry IDs are recorded; bodies remain on demand.
Observation is limited to 128 snapshots, 256 pending results, 4,096 seen call IDs,
64,000 body characters and 10,000 branch entries. The loader may retain a shorter
prefix; that entry has no complete snapshot. Exceeding a bound leaves proof
unavailable and does not change learning or execution. Preparation does not prove
wire delivery. A complete result does not prove physical file origin, model
attention, correct knowledge or task benefit; those fields remain unverified.
The native acceptance runner separately checks actual next-request content.
An automatically learned project Harness rule may be revised or retired only with
an exact predecessor revision, current user correction, positive/negative fixtures
and approval of the exact replacement by semantic review. A retired rule remains
as a disabled revision and in history. Manual or changed rules remain protected.
With automatic Harness application and semantic review enabled, an explicit lasting
correction in the current original user input is reviewed before task execution,
so the persisted correction can govern that task. This conservative nomination
requires the original input event to match the run prompt exactly; it grants no
authority by itself. Only exact auto-owned revisions can be updated, under one
230-second total deadline and the same complete semantic/fixture/transaction
checks. A held or failed review preserves the old policy and every cost; it never
acknowledges the unfinished task. Ordinary task write calls must preserve
owned declarations and markers; explicit previewed /harness authoring remains
available. This is a tool boundary, not a shell or filesystem sandbox.
Phase policies and history
All three automatic phases default to apply, preserving existing behavior.
propose validates and saves a private plan without changing learned files;
off skips that phase. For example, setting the Harness phase to propose from the /learning
policy view leaves automatic Memory and AGENTS.md behavior unchanged. Policies are stored in
<agent-dir>/memory/settings.json under automaticPhases, keyed by memory,
harness and agents. An explicit request through /learning and full maintenance still apply
validated current plans; the existing agentsMd.disabled setting remains
authoritative. AGENTS extraction is saved as a proposal if it would write to
a Memory or Harness phase configured to propose or off.
Incremental Memory planning and repair use the same exact proposal schema. A bounded repair must preserve recognizable proposal names and selected operations, including existing rewrite/delete intent; an empty replacement cannot silently discard them. Failed repairs retain both rejection reasons in bounded, sanitized private diagnostics. Representation validation permits at most one structural correction, followed by at most one separate semantic correction if complete review holds the accepted plan. Neither phase replans or loops. Each correction keeps its own receipt usage and cost, and only the final accepted attempt owns applied operations. Structural rejection metadata and screened structural response remain available even if later semantic correction succeeds. All original final validation and mutation gates remain mandatory. Citation-location rejection supplies up to eight parent-controlled candidate/citation positions and reasons to that same correction, including range and extracted-quote bounds; it never includes source text in diagnostics or raises the 2,000-character quote limit. Long encoded source lines are shown as complete numbered chunks; explicit offsets inside one line let the parent extract original characters without model transcription or decoding.
For a held private project body, the semantic worker can select sourceExcerpt
instead of generating content when the parent explicitly enables that candidate.
The selection requires explicit original citations from the bound current-source
audit. The parent checks the complete source hash and regular-file identity, then
copies the selected bytes into a neutral excerpt. Locked metadata stays unchanged.
This alternative uses the existing correction attempt. It grants no approval:
complete predecessor preservation, body, source, privacy and transaction checks
still govern writes. Ordinary historical reads cannot supply this correction.
Harness also permits one read-only repair when structured output is missing or a parsed plan fails validation. It uses the original frozen evidence and model; both worker attempts contribute to receipt usage, cost, and retry counts. Identity mismatches, ambiguous plans, output bounds, and cancellation remain terminal rejections.
Incremental Memory planners receive a parent-rendered JSON identity envelope; models fill the delta without calculating or retyping snapshot hashes. The parent still rejects any changed identity. Memory support questions retain each candidate's parent-validated original citation indexes and exact quotes alongside complete source entries. Quotes do not establish additional claims by themselves. Harness counter-evidence windows check contradictions, narrowing and revocation; lasting authority and matcher scope remain separate checks against the cited user evidence. An irrelevant window need not repeat authorization. These changes retain the existing probability, confidence, privacy and complete-evidence gates; they do not establish that learning improves later tasks. Source comments establish reported source reasoning, not independent proof of an external defect. Planning and bounded repair distinguish that from observed configuration/conditional behavior and avoid persisting historical test counts as lasting guarantees.
For a new literal addRule only, a nonempty message that is a strict prefix of its
single validated original user quote may be completed to that exact quote before
semantic review. Only display wording changes. Corrections, updates, complex
matchers, multiple citations and sensitive text are excluded. Both pre-completion
and completed plans are retained privately; the completed actual candidate is
revalidated and passes the same authorization, scope, privacy and complete
counter-evidence checks before application. The exact-quote wording check grants
no execution authority.
The opt-in real continuous-project study gives both arms the same experimental parent tool cap: eighteen admitted calls, followed by an empty active tool set. Excess calls already in a batch are blocked and counted as task failures. Original observations remain in the same session; independent learning workers and semantic review are unchanged. The standalone version-execution instruction is scoped to correction/retirement tasks: both orientation models had interpreted a conditional shared instruction as an immediate request, so that earlier cohort remains a distinct protocol. Earlier prompt-only-budget cohorts and their failures/costs remain separate evidence because this changes the experimental protocol. This study cap is not a production default or an automatically learned project rule. Correction/retirement tasks must also produce a successful standalone version probe in the real model session. An attempted call or a post-learning rule-engine decision does not establish that the task actually executed its requested probe.
Settings are strictly schema- and path-validated. A missing settings file keeps
automatic learning enabled; malformed, unknown, unsafe, or unreadable settings
disable learning and show a repair diagnostic instead of silently using defaults.
The learning backlog is a private, scoped reference index: its JSONL file is
capped at 4 MiB, each record at 4 KiB, and a full file rejects new entries
without silently deleting older ones. New records carry the project scope key
and use a scope-specific cursor. Legacy records require a bounded session-header
scope check; the historical global cursor is consulted only for those legacy
records and never consumes a scoped record. Unscoped or malformed records are
reported. Appends and cursor updates share a private process lock; contention
refuses the write without delaying the user task, and cursors cannot decrease.
Backlog inspection is status-only; /consolidate backfill retries bounded
learning work from verified original evidence and does not replay task tools. Full state
checks validate settings, backlog limits, scope binding, malformed references,
and cursor updates before status is shown.
The scope key is a readable flat identity: it strips the leading slash, replaces
path separators and colons with dashes and folds every run of whitespace or
control characters into one dash. A project such as ~/Documents/Home Lab/1984
therefore stores under --Users-FradSer-Documents-Home-Lab-1984--, never under a
path containing a literal space, tab or newline. Paths without whitespace keep
their existing name. Pi core's sessions/ directory and the goal package's
goals/ directory use their own naming and are not owned by this package.
The learning/ root keeps only cross-session state: the backlog index, its
scoped cursor and completion acknowledgments, and attempt ledgers that retain
receipts for crash recovery and cost accounting. Read-only backlog and replay
probes never create a project scope directory, a released replay lease removes
an empty scope directory, and lock/lease files are deleted on release. A scope
directory holding a completion record or attempt ledger is never removed.
Applied mutations and proposals are recorded privately under
<agent-dir>/memory/history/<escaped-canonical-cwd>/. History includes exact
before/after bytes, including indexes and mirror repairs. New pipelines attach an
exact parent-owned batch identity; the native Recent learning menu groups these
records and distinguishes index setup from learned knowledge. One learning can
therefore create several file-change records. Older records stay individually
accessible, and undo still previews and confirms one exact change at a time;
there is no batch mutation or grouping inferred from timestamps. /memory history
lists the latest 50 records; passing an id shows a bounded preview. Proposal
records are inspection artifacts; running /consolidate creates a fresh plan
against current evidence instead of replaying a stale proposal.
/memory evaluate reads the suite path explicitly supplied by the user, relative
to the project or absolute, using a bounded regular-file read. It performs no
model calls and does not change learned files.
Undo requires all affected files to match the recorded successor, validates
project scope and Memory privacy, and runs under the consolidation lock. It
refuses later edits, symlinks and invalid records. TUI use confirms a concrete
preview; headless use requires the id and --yes. Interrupted undo is recovered
to the applied state on the next learning session, unless an unrelated edit
requires inspection. Pending records from failed mutations cannot be undone.
If an interrupted mutation leaves bytes or permissions different from its recorded
predecessors, subsequent learning stops with a history id for inspection. Existing
AGENTS.md transaction recovery runs first. Reconcile these files to their exact
predecessors after review to resume; the incomplete record becomes abandoned.
Unknown current bytes are never automatically attributed to learning or overwritten.
History rejects detected credentials in proposals and file snapshots, matching
assigned values and provider key formats rather than ordinary prose, wiki links
or workflow permission names. A refused snapshot names the learned surface to
clean without echoing the matched bytes. Completed runs keep their run directory
(identity, task, plan, receipts, snapshot) for inspection, like a failed run keeps
its diagnostics.
Older changes made before history was installed have no undo record.
New applied Memory history can retain a parent-observed origin binding. It links
the complete frozen task, plan, manifests and receipts by their exact hashes and
records the file revisions before and after the mutation. This metadata stays in
private history. Missing or inconsistent artifacts mark origin unavailable;
legacy records gain no inferred origin. Undo still compares bytes and mode.
A read-only local interface can recover the complete creation and rewrite tasks
only through an unbroken, unique file-revision chain. It refuses incomplete or
changed evidence, cancellation, and configured bounds instead of returning a
partial history. It checks the complete captured inventory again before reuse.
With explicit private review authorization, normal Memory review and its bounded
correction worker receive complete relevant historical tasks in a separate
historicalMemoryOrigins field. The parent screens the full history for sensitive
data before projection and checks its binding again after asynchronous work.
History explains predecessor purpose and conditions; it does not establish current
facts, support citations, read access, permission to rewrite knowledge, or learning
benefit. Current evidence and every semantic gate remain required. Legacy gaps
gain no inferred context. Initial planning, CREATE-only review and historical
byte-bounded requests do not acquire this context.
Independent learning evaluation
/memory evaluate examples/learning-evaluation.json compares embedded baseline
and candidate Harness configurations against user-authored held-out cases.
The report includes accuracy, false blocks, missed protections, regressions and
configuration/suite digests. Cases support Bash decisions and skill/text matches.
No commands or models execute. These cases are independent of a planner's own
validation examples; passing them measures the configured rules, not model quality.
For an explicit paired model-task experiment, run from this package directory:
uv run --no-project scripts/evaluate-learning.py examples/learning-task-evaluation.json --validate
uv run --no-project scripts/evaluate-learning.py examples/learning-task-evaluation.json --model <provider/model> --output /tmp/learning-evaluation.json
Each task runs once per arm in a fresh disposable Git project with supplied Memory
snapshots, automatic learning disabled, and only the read tool. Authentication
and model configuration are frozen in one private snapshot for the whole suite;
each task receives a separate copy so runtime refreshes stay isolated.
The report includes literal-answer success, regressions, latency and observed
token usage/cost; missing prices remain unavailable. Output files are private and
never overwritten. Without --model, the configured continual-learning.json model is used.
The included synthetic example verifies exact answer scoring and native Memory
body-read evidence; use representative held-out tasks for your project. One
paired sample per task does not establish statistical or causal improvement,
learning-pipeline persistence, or Bash enforcement.
Verifying it is actually effective
One question the rest of this package's verification deliberately does not ask, because it is not a plumbing question:
python3 packages/continual-learning/tests/live_effectiveness.py
- Does persisted Memory change behaviour? Held-out tasks run once with no
Memory and once with it. Candidate cases require a successful native
readresult containing a marker from the Memory body. This is bounded paired evidence, not a statistical or causal claim about learning generally. The suite isexamples/learning-effectiveness.json.
The suite is committed rather than generated so the tasks are held out of the
corpus they test. It uses the model configured in continual-learning.json.
Memory
Exactly two roots participate:
- Complete canonical private root:
<agent-dir>/memory/<escaped-canonical-cwd>/. - Safe Git-trackable mirror:
<canonical Git project root>/.memory/.
The project mirror is enabled only at the canonical Git root. There is no
project-local private Memory root. Safe entries synchronize byte-identically;
private entries exist only in the private root and are marked (harness only)
in its MEMORY.md. Preferences stay private; credentials and secrets are never
stored, including in private files or evidence.
The root name uses Pi's flat path escaping: strip the leading slash, replace
separators and colons with -, and wrap with --. Names beyond 240 bytes fail
explicitly; no hash fallback exists. Paths with the same escaped name share the
root, lock and run storage. Obsolete roots are neither discovered nor migrated.
Before planning, newer-mtime-wins drift normalization synchronizes safe entries;
ties prefer the private copy. A tracked project-shared entry with no private copy
is new knowledge arriving through the git-tracked mirror: it is imported
byte-identically into the private root and reported as a repair, never deleted.
Only harness-only files leaked into the shared mirror are removed. Pre-run
normalization never deletes user Memory outside the parent-owned /consolidate
transaction, whose delete operations require a verified staleness verdict,
preservation, rollback, receipts and privacy checks. Deleting a shared Memory
entry during normalization cannot appear in a learning receipt, so it is
forbidden rather than merely reported. Normalization also runs when the private
root is absent, importing every committed shared entry.
Retrieval and descriptions
The default index injection budget is 6,000 characters. Entries list only a filename and description, without per-entry source suffixes. Case-insensitive filename deduplication prefers the private copy across locations. A compact root list supplies read routing; omission counts and complete-index pointers appear only when entries are omitted. Relevant bodies require explicit bounded reads.
Each body root is declared once and every entry row names its filename, so the budget reaches relevance metadata instead of repeating an absolute read path per entry. New descriptions should front-load a concise evidence-backed fact or preference, naming its subject and applicable project/context, in one line of at most 400 characters. A bare relevance trigger is insufficient: preserve material conditions and exceptions in the summarized claim, with full detail in the body. Several related grounded claims may share the bound so the index carries more than a bare pointer. An oversized description is refused before any write and regenerated; it is never silently truncated. Existing legacy descriptions are retained when they fit, or shortened with a single-line marker rather than silently losing a late trigger. Under budget pressure every listed entry stays reachable and cues give way before entries do.
The loader reports unique entry counts and file-read omissions; final formatting
reports budget omissions. Discovery pointers name MEMORY.md and exact roots
for bounded reads/listing. Indexes are discovery metadata and can be stale;
individual bounded files remain the authority. Parent rebuilds include descriptions
in complete indexes. Loading memory never writes indexes. All retrieved content
is explicitly untrusted reference data, not instructions.
Loading runs on every user turn, so it avoids repeat work without weakening its
checks: the read buffer is sized from the file rather than from the byte bound,
unchanged entry metadata is reused in-process while its device, inode, size,
mtime, and ctime still match a regular non-symlink file, the root identity is
re-verified for every real read and for the batch, and the git root probe is
memoized per canonical project path within a bounded window. A rewritten,
replaced, or symlinked entry is always read again or dropped, never served from
reuse.
Only strict [A-Za-z0-9][A-Za-z0-9_-]*.md basenames are entries; MEMORY.md is
metadata. Symlinks, non-regular files, escapes, and root replacement are rejected.
Index rows use the Markdown link target as their identity, regardless of display
label; a row without a vali