diff --git a/.github/workflows/learning-ci.yml b/.github/workflows/learning-ci.yml index 0bf8efb37..78844522f 100644 --- a/.github/workflows/learning-ci.yml +++ b/.github/workflows/learning-ci.yml @@ -16,6 +16,20 @@ jobs: fail-fast: false matrix: node: [24, 26] + services: + postgres: + image: postgres:17.12-bookworm + env: + POSTGRES_USER: replica + POSTGRES_PASSWORD: replica + POSTGRES_DB: replica_learning_test + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -h 127.0.0.1 -U replica -d replica_learning_test" + --health-interval 5s + --health-timeout 5s + --health-retries 10 defaults: run: working-directory: packages/learning @@ -29,8 +43,9 @@ jobs: - run: npm ci --ignore-scripts --engine-strict - run: npm run schema:check - run: npm test - - run: npm run demo - - run: npm run demo:agent-memory-repo + - run: npm run test:database + env: + REPLICA_LEARNING_TEST_DATABASE_URL: postgresql://replica:replica@127.0.0.1:5432/replica_learning_test - name: Brand check environment tests if: matrix.node == 24 working-directory: packages/learning/environments/brand-check diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7f8e1a6b6..e9ae0b6cf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -84,7 +84,6 @@ cd packages/learning npm ci npm run schema:check npm test -npm run demo ``` `npm ci` also installs the optional Copilot SDK, which labels review comments; the tests replace it with a stand-in, so they need no Copilot access. After changing a schema in `contracts/v1`, run `npm run schema:generate` and commit the regenerated `src/contracts-validators.cjs`. Hub's `npm run lint` lints and checks the formatting of this package. A new memory provider must pass the conformance suite described in [the package guide](packages/learning/README.md). diff --git a/docs/adr/0001-learning-extension-architecture.md b/docs/adr/0001-learning-extension-architecture.md index a7e6ad54c..3177f6af6 100644 --- a/docs/adr/0001-learning-extension-architecture.md +++ b/docs/adr/0001-learning-extension-architecture.md @@ -52,23 +52,23 @@ We chose this split so that consent and purpose rules exist in one place. If eve A provider declares a manifest with its contract versions, capabilities, storage kind, and the hosts it sends data to. The store refuses a provider without the seven required capabilities. Optional capabilities, such as semantic, graph, or temporal search, leave room for Graphiti, Mem0, or a Hub provider without changing the contract. -A SQLite provider on the driver built into Node.js 24 is the default. A JSON Lines provider, whose files a person can read, is the reference, and an in-memory provider serves tests. A fourth provider in the tests is written only from the contract, with no imports from the package. All four pass the same conformance suite, which ships as `@github/replica-learning/conformance` and includes adversarial cases: damaged withdrawals, forged approvals, forged evidence pins, and racing replacements. +A SQLite provider on the driver built into Node.js 24 is the default. A PostgreSQL provider uses the package-owned `replica_learning` schema for hosts that need a shared database. A JSON Lines provider, whose files a person can read, is the reference, and an in-memory provider serves tests. Another provider in the tests is written only from the contract, with no imports from the package. The conformance suite ships as `@github/replica-learning/conformance` and includes adversarial cases: damaged withdrawals, forged approvals, forged evidence pins, and racing replacements. The [learning guide](../../packages/learning/README.md#postgresql-storage) describes PostgreSQL setup and retention. ### Consolidation is separate from memory A consolidator, sometimes called a dreamer, reads evidence and proposes learnings. It is not a store. It receives a frozen view of the evidence the purpose may use. The view shows a memory's content, evidence, and counterevidence only while that evidence permits the purpose, so a consolidator cannot reuse withdrawn knowledge. The store gives it no write access and saves everything it returns as proposed. A consolidator is code a team chooses to run; the frozen view is not a sandbox. -The reference consolidator is deterministic: it proposes labeled themes with observed problems in at least two threads, two prototypes, and two reviewers, and holds back contested themes. When an accepted learning for a theme has stopped applying, a new proposal offers to replace it. A model-based consolidator, such as SkillOpt-Sleep or #230's discovery passes, can plug in behind the same interface. A consolidator module receives the built-in consolidators along with its options, so it can build on them without importing the package. - -`packages/learning/examples/agent-memory-repo` shows the pattern with [Agent Memory Repo](https://github.com/AgentMemoryRepo/agentmemoryrepo), an open format whose Dreaming agent adds patterns and cleans up duplicates, outdated entries, and contradictions. Its Dreaming consolidator proposes merges, and reports learnings that look alike but conflict, or that are outdated or contested, for a person to act on, because Replica keeps the rule that only a person decides. Records stay append-only; recall stops using what a person merged away or retired. Its publisher copies accepted learnings into a memory repo other agents read. The memory repo is a publishing target, not a record store, since its Markdown entries have no versions, digests, or consent records. +The reference consolidator is deterministic: it proposes recurring themes from relevant feedback and holds back contested themes. By default, a theme needs at least two threads or agent sessions; a checkout using a local store needs only one. One prototype and one reviewer are enough. The [learning guide](../../packages/learning/README.md#bring-your-own-consolidator) explains which feedback counts and how to change the thresholds. When an accepted learning for a theme has stopped applying, a new proposal offers to replace it. A model-based consolidator, such as SkillOpt-Sleep or #230's discovery passes, can plug in behind the same interface. A consolidator module receives the built-in consolidators along with its options, so it can build on them without importing the package. ### Evidence -Each Hub review thread becomes an episode pinned to its Hub, repository, prototype, branch, and the Build the reviewer saw. Comments, labels, status changes, and retractions are append-only events. An edit adds a version that supersedes the old one. A deletion adds a retraction that removes the earlier versions, and labels on them, from every purpose. Events carry a separate `payloadDigest`, and an event's digest leaves out its payload and any redaction note, so a provider can remove a payload later, record why, and keep the digest intact. A redacted event is never evidence. Labels and retractions name their target in `parentEventId`, which the digest covers and validation matches to the payload, so a redaction never loses what a label judged or a retraction removed. Reviewer names and avatars are dropped, and only Hub's compact target fields are kept. +Each Hub review thread becomes an episode pinned to its Hub, repository, prototype, branch, and the Build the reviewer saw. Comments, labels, status changes, and retractions are append-only events. An edit adds a version that supersedes the old one. A deletion adds a retraction that removes the earlier versions, and labels on them, from every purpose. Events carry a separate `payloadDigest`, and an event's digest leaves out its payload and any redaction note, so a provider can remove a payload later, record why, and keep the digest intact. A redacted event is never evidence. Labels and retractions name their target in `parentEventId`, which the digest covers and validation matches to the payload, so a redaction never loses what a label judged or a retraction removed. Reviewer names and avatars are dropped, and only Hub's compact target fields are kept. A coding agent session is also an episode: its user and agent messages and its outcome are events, tool calls and output are skipped, and well-known secrets are removed before anything is stored. Removing a comment uses that rule. A provider with the optional `observation.redact` capability implements one more method, `redactRecord`, which replaces a stored event with a copy that has the same ID and digest, no payload, and a redaction note, and refuses anything else. The store's `redactComment` asks for a person and a reason, redacts every version of the comment and every label on them, audits it, and reports the accepted learnings that need rebuilding and the exports that copied the comment or a learning citing it. It finds versions by edit links inside the thread and by Hub comment ID, and refuses a history that links two comments or leaves the thread, because guessing could remove someone else's words. Each redaction note keeps the version's Hub comment ID, which the digest does not cover, so the other versions can still be found after the text is gone. Because the store relies on it, a provider refuses a note whose comment ID differs from the payload it removes, and a note on any other event that names one. Each removal gets one audit entry whose ID and content come from the event's stored note, so a retry or a racing call writes the same entry and the provider keeps one. The follow-ups depend only on what cites the comment, so running it again after a failure finishes the removal and reports them again. Re-importing an old snapshot cannot restore the text, because the importer skips events the store holds. A host that erases deleted comments can ask an import to remove the text of every comment its snapshot shows as deleted, recorded as the importer's action, and the next such import finishes a removal that failed part way. A host can also remove one comment by its Hub comment ID, which imports nothing and so needs no active grant. A host must not redact while an import or labeling of the same store is in progress. A redaction reads the comment's events before it removes their text, so text stored in between stays. For a comment deleted at its source, later imports must ask to remove deleted text, which removes what stayed. Hub meets both: its runs and its deletion job take turns through one job queue key, and its imports always ask to remove deleted text. We chose a payload-free copy over deletion so that every digest, approval, and audit entry that names the event still verifies. -Scope is the repository's host and owner/name, taken from the checkout's origin remote, and episode IDs include it. A host that keeps stores outside checkouts, such as Hub, names the repository instead, after checking the person's access itself. The same owner/name on two hosts therefore never shares records, even in one provider. Hub names each repository by its stable GitHub ID, so renaming or transferring the repository keeps its learnings. Hub logs name only owner/name, so the importer checks the repository and relies on the checkout for the host. +GitHub-backed scope is `github.com/repositories/`; local-only scope is `local/repositories/`. Episode IDs include the scope. In a GitHub-backed checkout, the GitHub CLI resolves the origin remote once and the local config keeps the ID. A host that keeps stores outside checkouts, such as Hub, names the repository instead, after checking the person's access itself. Renaming or transferring a GitHub repository keeps its learnings. + +Hub's repository UUID establishes which existing SQLite store belongs to the GitHub ID. A checkout's old owner/name cannot establish that identity after a rename or transfer, so a person confirms it before migration. SQLite moves the scope in one transaction and fences old writers. Other providers cannot enforce that fence on older clients, so the operator stops them and runs the offline copy described in the [learning package guide](../../packages/learning/README.md). The copy is verified before the config switches, and the original remains available. An evidence reference must resolve to stored events inside the episode it names. The store rebuilds its source pin, time, and author from storage and refuses a proposal that states different ones, so a proposer cannot move evidence to another prototype or Build. @@ -82,9 +82,9 @@ Deciding at read time lets a later grant cover earlier evidence when a team says ### Approval -A learning has two digests. `contentDigest` identifies the learning itself: its scope, kind, content, targets, lifecycle, evidence, and validity dates. `reviewDigest` covers everything a reviewer is shown, adding its support, dissent, confidence, rationale, and proposer. Accepting or rejecting requires the `reviewDigest` the person reviewed, so new support or dissent makes an older review stale and the proposal gets a new version. An edit binds the approval to the new content's `contentDigest`. +A learning has two content-related digests. `contentDigest` identifies the learning itself, including its optional title. Untitled historical records keep their original digests. `reviewDigest` covers everything a reviewer is shown, adding support, dissent, confidence, rationale, and proposer. Accepting or rejecting requires the `reviewDigest` the person reviewed. Editing or reinstating requires the exact record `digest`, so later decisions cannot reuse a stale review. An edit binds a new approval to the updated content. -The contracts require a human on every grant, withdrawal, approval, rejection, retirement, and export. The store also checks each learning's history: it must start as a proposal, each decision must name the version it reviewed, and each step may change only its own fields. Accepting may change the text and nothing else, records `edited` exactly when it does, and replaces only what the reviewed lifecycle names. Only accepted learnings carry `supersedes`, so a proposal cannot smuggle in a replacement its `reviewDigest` does not show. A sealed record that breaks these rules is never used, and reading one shows only strictly checked identifiers and digests, never content, for the current version and every past one. The local command cannot authenticate people, so it records those identities as asserted. +The contracts require a human on every grant, withdrawal, approval, rejection, retirement, and export. The store also checks each learning's history: it must start as a proposal, each decision must name the version it reviewed, and each step may change only its own fields. A person can edit an accepted title or text with a reason, or reinstate a rejected or retired learning while its evidence still permits instruction. Both decisions append approved versions. Only accepted learnings carry `supersedes`, so a proposal cannot smuggle in a replacement its `reviewDigest` does not show. A sealed record that breaks these rules is never used, and reading one shows only strictly checked identifiers and digests, never content, for the current version and every past one. The local command cannot authenticate people, so it records those identities as asserted. ### Supersession @@ -108,13 +108,13 @@ Learning happens first in explicit, inspectable memory. A training-purpose expor ## Consequences -- Hub runs the explicit learning loop through the package boundary. Teams can swap the provider, labeler, or consolidator by configuration without changing core logic. In a checkout, every step except labeling with Copilot works offline. -- One damaged policy record blocks every learning operation until someone repairs it. That is deliberate; a store that keeps running on damaged consent records can restore permissions nobody granted. +- Hub runs the explicit learning loop through the package boundary. Teams can swap the provider, labeler, or consolidator by configuration without changing core logic. After the checkout's GitHub repository ID is saved, a local store works offline except for Copilot labeling, scoring, and update drafting. +- A damaged policy record blocks every learning operation that reads it until someone repairs it, and `verify` checks every record. That is deliberate; a store that keeps running on damaged consent records can restore permissions nobody granted. Decisions read only the records tied to their evidence, so they stay fast as a store grows. - Providers, labelers, and consolidators are trusted code. The store limits what they are given and re-checks what they return, but it does not sandbox them. - Inside a checkout, learning data and exports live only under `.replica/`, after following links, and only when Git ignores that exact path. The checkout root and names that merely start with two dots count as inside. Git ignoring a path is not enough, since a dev server or build may still serve it. - The command asserts identities. An integrating host must pass only identities and repository authority it authenticated. - The generated validator file is large, as in `packages/controls`. -- SQLite is the default local provider. A host that needs another database implements the provider interface and runs the conformance suite against it. +- SQLite is the default local provider. PostgreSQL is available for a shared database; another provider implements the same interface and runs the conformance suite. - Copilot credential custody, billing, subprocess isolation, and deployed authentication remain integration decisions for the new Hub layer. ## Alternatives considered @@ -126,7 +126,7 @@ Learning happens first in explicit, inspectable memory. A training-purpose expor - A knowledge graph or vector store as the default. Rejected; the default should be simple and local, and graph or semantic search can arrive as provider capabilities. - An agent collects comments through the canvas, and a starter skill runs each step. Replaced: a person had to start every step, and every comment passed through an agent session, which cost tokens and could introduce copying errors. - Billing Copilot to the organization through the App's installation token. Deferred: it needs the App's Copilot requests permission and an installation on every repository in the organization. -- PostgreSQL or Neo4j providers in this version. Deferred: SQLite meets one Hub's needs, and the provider interface and conformance suite let a team add one later. +- Neo4j as a built-in provider. Deferred; the provider interface and conformance suite let a team add one later. - Model-only consolidation. Kept as a plug-in option; the reference stays deterministic so tests and reviews are reproducible. ## Next steps diff --git a/hub/script/check-image/index.ts b/hub/script/check-image/index.ts index b5e7759d5..879910680 100644 --- a/hub/script/check-image/index.ts +++ b/hub/script/check-image/index.ts @@ -59,7 +59,7 @@ export async function checkImage() { image, "sh", "-c", - 'test -w /app/storage/learning && test -f /opt/replica/learning/bin/replica-learning.mjs && cd /opt/replica/learning && node --input-type=module -e \'import {readFile} from "node:fs/promises"; await import("@github/copilot-sdk"); const manifest = JSON.parse(await readFile("node_modules/@github/copilot-sdk/package.json", "utf8")); if (manifest.version !== "1.0.28") process.exit(1)\'', + 'test -w /app/storage/learning && test -f /opt/replica/learning/bin/replica-learning.mjs && cd /opt/replica/learning && node --input-type=module -e \'import {readFile} from "node:fs/promises"; await import("@github/copilot-sdk"); const manifest = JSON.parse(await readFile("node_modules/@github/copilot-sdk/package.json", "utf8")); if (manifest.version !== "1.0.34") process.exit(1)\'', ) docker("network", "create", network) networkCreated = true diff --git a/packages/learning/README.md b/packages/learning/README.md index 408e973d1..3fad8daee 100644 --- a/packages/learning/README.md +++ b/packages/learning/README.md @@ -1,32 +1,21 @@ # Replica learning -`@github/replica-learning` lets Replica learn from review evidence without training a model. It owns the version 1 learning contracts, the memory provider interface, built-in SQLite, JSON Lines, and in-memory providers, two reference consolidators, a conformance suite, the `replica-learning` command, and an example that plugs in [Agent Memory Repo](examples/agent-memory-repo/README.md). It also prepares training for a team that chooses to post-train a [decision model](#decision-model). It isn't published to npm yet, so run it from a Replica checkout with a Node.js version matching `engines.node` in [package.json](package.json). +`@github/replica-learning` lets Replica learn from review evidence without training a model. It owns the version 1 learning contracts, the memory provider interface, built-in SQLite, PostgreSQL, JSON Lines, and in-memory providers, two reference consolidators, a conformance suite, and the `replica-learning` command. It also prepares training for a team that chooses to post-train a [decision model](#decision-model). It isn't published to npm yet, so run it from a Replica checkout with a Node.js version matching `engines.node` in [package.json](package.json). The design and its trade-offs are in [ADR 0001](../../docs/adr/0001-learning-extension-architecture.md), and the decision model's in [ADR 0002](../../docs/adr/0002-decision-model-and-rl-environment.md). ## What the first loop does -The package turns saved Hub review comments into guidance that a person approved. Its CLI, providers, and demos work independently. The [new Hub](../../hub/README.md) captures complete repository review snapshots and runs the explicit learning loop through this command boundary. +The package turns feedback into guidance that a person approved. The feedback can be saved Hub review comments or, when you work alone, your own chats with a coding agent. Its CLI and providers work independently. The [new Hub](../../hub/README.md) captures complete repository review snapshots and runs the explicit learning loop through this command boundary. 1. A person records consent for named purposes, such as review and instruction. 2. A host imports one complete snapshot of a repository's comments. Each review thread becomes an episode pinned to its prototype and to the Build the reviewer commented on. -3. A labeler, Copilot by default, labels design themes. A consolidator proposes the themes that recur across distinct threads, prototypes, and reviewers. +3. A labeler, Copilot by default, labels design themes. A consolidator proposes the themes that recur in at least two threads or agent sessions. When you work alone, one session is enough. 4. A person accepts, edits, or rejects each proposal against the digest they reviewed. 5. Agents recall the accepted learnings when they build the next prototype. Nothing is accepted automatically. Nothing is published or used for training without a grant for that purpose. No model weights change. -## Try it - -```sh -cd packages/learning -npm ci -npm test -npm run demo -``` - -The demo runs the whole loop on synthetic comments in a temporary checkout and prints every command with its output. `npm run demo:agent-memory-repo` adds Dreaming, which merges duplicate learnings, and publishes the result to a memory repo other agents can read. - ## Run it yourself To run the commands in a prototype checkout, which keeps its data under `.replica/learning/`, use Node: @@ -38,17 +27,31 @@ node /packages/learning/bin/replica-learning.mjs doctor | Command | What it does | | --- | --- | | `doctor` | Shows the scope, the provider, where data goes, and why each was chosen | +| `migrate` | Sets up the package-owned PostgreSQL schema using a privileged environment-supplied URL | +| `import-sqlite --offline` | Copies a stopped Hub SQLite store and its migration mappings into PostgreSQL | | `grants add`, `grants list`, `grants withdraw` | Records, lists, and ends consent for purposes | -| `redact ` | Removes a comment's text when a person asks: every version and its labels | +| `redact ` | Removes a review comment's or agent session event's text when a person asks: every version and its labels | | `redact --comment ` | Removes the same text for a Hub comment named by its Hub ID. It imports and labels nothing and needs no active grant. `--reason` defaults to the comment being deleted at its source. `removed` in the `--json` output counts the events whose text it removed, 0 when none was left. Run it only while no import or labeling of the same store is in progress | | `import hub-comments ` | Imports a logged snapshot from the canvas comment actions. `--redact-deleted` also removes the text of comments the snapshot shows as deleted | -| `label` | Labels, with Copilot or the configured labeler, each comment it has not been asked about, and reports what it cost. `--since` skips older comments, and `--max-requests` stops after that many labeler requests | +| `import agent-session ` | Stores one coding agent session as evidence: the user and agent messages in order, and its outcome. It skips the task, tool calls, and tool output, removes well-known secrets such as tokens and private keys, and keeps at most 10,000 characters of each message. Sending the same `sessionId` again adds new messages and updates changed ones, but never restores a removed message. Optional `pickAndPolishNotes` stores each Pick & Polish note as its own episode under the same grant. Needs `--actor agent:` and a grant that names `agent_session` | +| `label` | Labels, with Copilot or the configured labeler, each comment it has not been asked about, and reports what it cost. `--relabel` asks about existing comments again and supersedes this labeler's earlier judgments. `--since` skips older comments, and `--max-requests` stops after that many labeler requests | | `label ` | Records theme labels someone else wrote | | `copilot status` | Shows whether Copilot answers here, as whom, and with which models | | `consolidate --from