@@ -94,6 +94,15 @@ 把这次反馈,变成下次的习惯<
把这次反馈,变成下次的习惯<
查看修改前后的差异
+
+ 复测报告
合成验收
+
+
+
+ 查看冻结的 AGENTS.md 原文
+
+ 项目、任务和报告编号
+
复测报告
合成验收
+
+
+
查看冻结的 AGENTS.md 原文
项目、任务和报告编号
diff --git a/console/static/personal.js b/console/static/personal.js
index 1bfde793..1e78303d 100644
--- a/console/static/personal.js
+++ b/console/static/personal.js
@@ -16,6 +16,20 @@
let evidenceSelection = [], evidenceQuery = 0, receiptSelection = 0;
let proposalCapability = {status: 'unconfigured'}, viewedFeedback = '';
const historyButtons = new Map();
+ const detailKey = 'hg-personal-current-proposal';
+ function rememberDetail(value) {
+ try {
+ if (value) sessionStorage.setItem(detailKey, JSON.stringify(value));
+ else sessionStorage.removeItem(detailKey);
+ } catch (_) { /* Opening a history entry also works with storage disabled. */ }
+ }
+ function savedDetail() {
+ try {
+ const value = JSON.parse(sessionStorage.getItem(detailKey));
+ const valid = id => typeof id === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(id);
+ return valid(value?.project) && valid(value.feedback) ? value : null;
+ } catch (_) { return null; }
+ }
const sourceRoles = {user: '用户原话', tool: '工具观测', assistant: '助手输出 · 未核实'};
const feedbackKinds = {explicit_request: '明确请求', correction: '纠正', success_observation: '成功观测', failure_observation: '失败观测'};
$('feedback').disabled = true; $('save-draft').disabled = true; $('submit-feedback').disabled = true;
@@ -38,6 +52,7 @@
const showMode = (next, focus = false) => windowController.show(next, focus);
function selectWorkspace(view) {
receiptSelection++;
+ if (view === 'records') { proposals.stop(); rememberDetail(null); }
document.body.dataset.view = view;
$('records-page').hidden = view !== 'records';
$('proposal-page').hidden = view !== 'proposal';
@@ -52,6 +67,7 @@
}
function collapseWindow() {
receiptSelection++;
+ proposals.stop(); rememberDetail(null);
$('bubble').hidden = true;
return showMode('bar');
}
@@ -96,7 +112,14 @@
signal,
...(value === undefined ? {} : {body: JSON.stringify(value)})
});
+ if (signal?.aborted) throw signal.reason;
if (response.status === 401) { $('pair').hidden = false; openWorkspace('records'); throw Error('请连接自己的本地服务。'); }
+ if (!response.ok && (path.startsWith('evolution/') || path.includes('/evolution/'))) {
+ const detail = await response.json();
+ const reasons = {out_of_scope: '找不到当前项目的审核回执。', question_closed: '问题已关闭,请重新查看任务。',
+ unavailable: '审核服务暂不可用。'};
+ throw Error(reasons[detail.code] || '审核回执暂时无法读取,请重新查看。');
+ }
if (response.status === 409) {
const detail = await response.json();
if (detail.code?.startsWith('proposal_')) throw Object.assign(Error('提案暂时无法生成。'), {code: detail.code});
@@ -119,11 +142,12 @@
});
const proposalRoute = (id, feedback) => `projects/${id}/feedback/${feedback}/proposal`;
const proposals = window.HGPersonalProposal.create({
- read: (id, feedback) => api(proposalRoute(id, feedback)),
- start: (id, feedback) => api(proposalRoute(id, feedback), {}),
- reply: (id, feedback, question, answer) => api(proposalRoute(id, feedback) + '/reply', {question_id: question, answer}),
- cancel: (id, feedback) => api(proposalRoute(id, feedback) + '/cancel', {}),
+ read: (id, feedback, signal) => api(proposalRoute(id, feedback), undefined, {signal}),
+ start: (id, feedback, signal) => api(proposalRoute(id, feedback), {}, {signal}),
+ reply: (id, feedback, question, answer, signal) => api(proposalRoute(id, feedback) + '/reply', {question_id: question, answer}, {signal}),
+ cancel: (id, feedback, signal) => api(proposalRoute(id, feedback) + '/cancel', {}, {signal}),
updates: (id, feedback, after, signal) => api(proposalRoute(id, feedback) + '/events', undefined, {after, signal}),
+ reviewApi: api,
render: state => {
$('proposal-card').hidden = !state;
$('return-proposal').hidden = !state;
@@ -132,9 +156,16 @@
viewedFeedback = feedback;
updateHistorySelection();
}
+ const review = state?.review;
+ const linked = Boolean(window.HGPersonalProposal.linkedJob(state?.proposal?.result));
+ const reviewDisplay = review || window.HGPersonalProposal.initialReview(state?.proposal);
+ window.HGPersonalProposal.renderReview(document, reviewDisplay &&
+ {original: state.proposal.result?.original_text, ...reviewDisplay});
+ $('review-identifiers').hidden = !review?.job;
if (!state) return;
const {message, detail = '', path = '', diff = '', fixture, question, cancellable} = window.HGPersonalProposal.describe(state.proposal);
- $('proposal-status').textContent = state.loading ? '正在查看提案状态…' : (state.error || message);
+ $('proposal-status').textContent = state.loading ? '正在查看提案状态…' :
+ (state.error || (linked && state.proposal.status === 'ready' ? '提案已生成' : message));
const badge = $('proposal-badge');
badge.hidden = !fixture && !diff;
badge.textContent = fixture ? '合成验收 · 只读' : '只读';
@@ -144,7 +175,7 @@
$('proposal-target').hidden = !path;
$('proposal-diff').textContent = diff;
$('proposal-changes').hidden = !diff;
- $('proposal-approval').hidden = state.proposal?.status !== 'ready' || !diff;
+ $('proposal-approval').hidden = state.proposal?.status !== 'ready' || !diff || review?.adoption === '已采用';
const additions = window.HGPersonalProposal.summarizeDiff(diff);
$('proposal-summary').replaceChildren(...additions.map(text => {
const item = document.createElement('li');
@@ -154,18 +185,24 @@
$('proposal-summary').hidden = !additions.length;
$('proposal-start').hidden = state.loading || Boolean(state.proposal) || proposalCapability.status !== 'ready';
$('proposal-start').onclick = () => proposals.show(state.project, state.feedback, true);
- $('proposal-refresh').hidden = !state.error;
- $('proposal-refresh').onclick = () => proposals.show(state.project, state.feedback);
- const canReply = Boolean(question) && proposalCapability.status === 'ready';
+ const canResume = review?.canResume === true;
+ $('proposal-refresh').hidden = !state.error && !reviewDisplay;
+ $('proposal-refresh').textContent = canResume ? '继续复测' : '重新查看状态';
+ $('proposal-refresh').onclick = () => proposals.show(state.project, state.feedback, canResume);
+ const reviewQuestion = review?.question?.open === true && review.question.prompt && review.question.question_id;
+ const currentQuestion = reviewQuestion || question;
+ const canReply = Boolean(reviewQuestion || (question && proposalCapability.status === 'ready'));
const form = $('proposal-reply'), answer = $('proposal-answer');
- if (canReply && form.dataset.question !== question) answer.value = '';
- form.dataset.question = question || '';
+ if (canReply && form.dataset.question !== currentQuestion) answer.value = '';
+ form.dataset.question = currentQuestion || '';
form.hidden = !canReply;
answer.disabled = Boolean(state.loading);
form.onsubmit = event => {
event.preventDefault();
- if (!state.loading && answer.value.trim())
- void proposals.reply(state.project, state.feedback, question, answer.value.trim(), state.proposal);
+ if (!state.loading && answer.value.trim()) {
+ if (reviewQuestion) void proposals.answerReview(state.project, state.feedback, state.proposal, reviewQuestion, answer.value.trim(), review);
+ else void proposals.reply(state.project, state.feedback, question, answer.value.trim(), state.proposal);
+ }
};
$('proposal-cancel').hidden = state.loading || !cancellable;
$('proposal-cancel').onclick = () => proposals.cancel(state.project, state.feedback, state.proposal);
@@ -209,12 +246,22 @@
: (proposalCapability.status === 'unavailable' ? '当前平台无法安全读取项目指令,仍可保存反馈和查看已有提案。'
: '已连接本地服务 · 可保存反馈和查看已有提案。');
capabilities(health.capabilities);
- const previous = project;
+ const saved = savedDetail();
+ const previous = project || saved?.project;
$('projects').replaceChildren(new Option('请选择项目', ''));
for (const row of health.projects) $('projects').add(new Option(row.root, row.id));
project = health.projects.some(row => row.id === previous) ? previous : (health.projects[0]?.id || '');
$('projects').value = project;
- await selectProject();
+ const selecting = selectProject();
+ const generation = selection, current = receiptSelection;
+ await selecting;
+ if (saved?.project === project && generation === selection && current === receiptSelection) {
+ try {
+ const receipt = await api(`projects/${project}/feedback/${encodeURIComponent(saved.feedback)}`);
+ if (generation === selection && current === receiptSelection && receipt.id === saved.feedback)
+ await showFeedbackProposal(project, receipt);
+ } catch (_) { if (generation === selection && current === receiptSelection) rememberDetail(null); }
+ }
}
async function selectProject() {
project = $('projects').value; cursor = 0; evidenceQuery++;
@@ -311,6 +358,9 @@
}
function showFeedbackProposal(projectId, receipt, generate = false) {
$('bubble').hidden = true;
+ rememberDetail({project: projectId, feedback: receipt.id});
+ $('review-identifiers').open = false;
+ $('review-original').open = false;
$('proposal-changes').open = false;
renderProposalFeedback(receipt);
void proposals.show(projectId, receipt.id, generate);
@@ -353,7 +403,13 @@
$('expand').onclick = () => { selectWorkspace('records'); return windowController.open(); };
$('details').onclick = () => openWorkspace('records');
$('proposal-records').onclick = () => openWorkspace('records');
- $('return-proposal').onclick = () => openWorkspace('proposal');
+ $('return-proposal').onclick = () => {
+ if (viewedFeedback) {
+ rememberDetail({project, feedback: viewedFeedback});
+ void proposals.show(project, viewedFeedback);
+ return openWorkspace('proposal');
+ }
+ };
$('collapse').onclick = collapseWindow;
$('minimize').onclick = () => native('minimize');
$('drag').onmousedown = () => native('drag');
@@ -361,6 +417,7 @@
$('ordinary').onclick = async () => { if (await native('ordinary')) showMode('details'); };
$('close-window').onclick = guarded(async () => {
receiptSelection++;
+ proposals.stop(); rememberDetail(null);
await drafts.flushAll();
if (desktop) await native('close'); else await collapseWindow();
});
@@ -411,7 +468,7 @@
collapseWindow();
}
});
- $('projects').onchange = guarded(selectProject);
+ $('projects').onchange = guarded(() => { rememberDetail(null); return selectProject(); });
$('pair').onsubmit = guarded(async event => { event.preventDefault(); token = $('token').value.trim(); await connect(); sessionStorage.setItem('hg-personal-token', token); $('token').value = ''; });
$('connection-file').onchange = guarded(async event => {
const file = event.target.files[0]; if (!file) return;
diff --git a/docs/personal-evolution-review.md b/docs/personal-evolution-review.md
new file mode 100644
index 00000000..f012d9c3
--- /dev/null
+++ b/docs/personal-evolution-review.md
@@ -0,0 +1,64 @@
+# Personal evolution review (offline C service)
+
+This review path is read-only with respect to the selected project. It freezes the selected
+`AGENTS.md`, registers a complete virtual candidate, runs the same reviewed Python command in
+two state-root workspaces, and persists both run records and one comparison report. A passing
+comparison sets `apply_eligible`; it does not authorize or apply a project write.
+
+## Empty-state demo
+
+Create a temporary project containing `AGENTS.md`, then run:
+
+```console
+harnessgrad personal evolution-demo \
+ --state-root /absolute/path/outside/the/checkout/state \
+ --project /absolute/path/to/the/temporary/project
+```
+
+The command uses only the built-in synthetic feedback and fixed Python text check. It prints one
+JSON receipt and exits 0 after a valid review receipt, including when the review conclusion is a
+failure. The output is marked `fixture: true` and `applied: false`. Repeating the command with the
+same state root and project replays the original job and report.
+
+The older calculator fixture remains available through `personal evolution-check`; it verifies
+that the baseline fails and the fixed candidate passes without involving the personal service.
+
+## Receipt linkage
+
+- The offline checker supports a B reproduction plan with scenario `python-related-tests`,
+ input `Review instruction text`, and expected text `Run related tests before delivery after
+ changing Python code.`. For a matching plan, `evolution_job` gives the stable C task identity
+ `(profile_id, project_id, job_id)`. The planner receives this reproduction object when
+ `instruction.md` is the sole selected surface. A retry reuses its original frozen prompt.
+- Other reproduction plans keep their ready proposal and diff. The result has
+ `evolution_job: null` and `evolution_review.status: unmeasured` with reason
+ `scenario_unavailable`. A matching plan with a criterion over the queue's 1,024 UTF-8 byte
+ limit uses reason `invalid_conditions`. The original criteria stay in the saved plan.
+- `GET /api/personal/projects/{project_id}/evolution/{job_id}` returns the current `JobView`.
+- If the service stops during a review, open the saved feedback in Desktop and select
+ **继续复测**. Replaying `POST /api/personal/projects/{project_id}/feedback/{feedback_id}/proposal`
+ with `{}` wakes the linked review under its original job ID and reuses completed phases.
+ Opening history reads the saved state. Resuming the offline check requires no model configuration.
+- `GET .../{job_id}/events?after=N` returns at most 50 strictly newer state events.
+- A terminal reviewed job includes `comparison_ref`; `GET
+ .../{job_id}/comparisons/{comparison_ref}` returns the report.
+- The report records the same `job`, frozen `snapshot_sha256`, `candidate_id`,
+ `candidate_sha256`, and the baseline/candidate `run_ref` values. Each run includes its input
+ digest, exact argument vector, exit code, bounded stdout/stderr, timeout reason, and source
+ integrity result.
+
+All reads are project scoped. An unknown job and a job owned by another project both return
+`out_of_scope`. Reports remain readable after service restart because artifacts, questions, jobs,
+events, and reports live in the C-owned `evolution.sqlite3` database.
+
+## Review states
+
+- `needs_input / missing_evidence`: answer once through `POST .../{job_id}/reply`; the original
+ job continues and an identical reply is idempotent at the storage boundary.
+- `not_comparable / execution_timeout`: one or both fixed runs timed out.
+- `not_comparable / scenario_mismatch`: the candidate cannot use the selected registered check.
+- `failed / stale_snapshot`: the selected project bytes changed after freezing.
+- `retest_passed`: the baseline failed and the candidate passed the same command and checker.
+
+Formal apply, rollback, version journal, native load evidence, and later-task behavior evidence are
+not part of this read-only milestone.
diff --git a/docs/personal-evolution.md b/docs/personal-evolution.md
index 2b62ab36..4fe730a9 100644
--- a/docs/personal-evolution.md
+++ b/docs/personal-evolution.md
@@ -313,3 +313,134 @@ call already admitted for dispatch may finish within its existing timeout;
cancellation prevents publishing a Diff.
Unconfigured services and platforms without safe reads can still record feedback
and reopen saved results. This flow leaves proposals unapplied and unverified.
+
+## Submit a selected learning decision to the local queue
+
+The trusted Python entry point is `PersonalService.open_learning(project_id, source,
+ask=..., read_existing=..., confirm_policy=..., reports=...)`. Register the project
+with the service first. This release selects the default profile, the project's
+root `AGENTS.md` and the `python-related-tests` scenario. The source adapter and
+reflection callback are supplied by the caller. Tests use a selected synthetic
+import and a scripted reply. Expanding the learning policy requires an explicit
+confirmation through the existing D1 verifier.
+
+```python
+learning = service.open_learning(project_id, source, ask=scripted_reply,
+ read_existing=read_existing, confirm_policy=confirm_policy)
+learning.intake.update_learning_policy(authorized_update)
+page = learning.intake.poll_source(learning.scope, source_id)
+for decision in page.receipts:
+ if decision.decision.status == 'triggered':
+ result = learning.submit_decision(decision.seq)
+ if result.job is not None:
+ view = learning.read_job(result.job.job_id)
+ events = learning.read_events(result.job.job_id, after=0)
+```
+
+On restart, obtain the original decision sequence from
+`learning.intake.store.read_receipts(learning.scope, after=...)` and call
+`submit_decision(seq)` again. Recovery reuses the saved candidate and queue key
+even after the source cursor advances. The state root holds the D1/D2 database
+(`learning.sqlite3`), C queue (`evolution.sqlite3`) and scoped immutable
+`evolution-artifacts/` records. D publishes the frozen inputs under their original
+references in C's artifact registry before submitting. C's worker checks the
+selected project bytes before executing the review. Read subsequent event pages
+using the previous `next_after`.
+
+`read_review(job_id)` returns `None` while the comparison is pending. The local
+service returns C's persisted comparison dictionary, including the baseline and
+candidate runs and captured output, after checking the job identity and D's frozen
+request. An explicitly supplied v1 report reader still returns a `LearningReview`.
+
+From a scratch directory outside the checkout, using PowerShell and Python 3.12+
+with pytest, set `$repo` to the checkout and run:
+
+```powershell
+$env:PYTHONPATH = $repo
+$env:PYTEST_DISABLE_PLUGIN_AUTOLOAD = '1'
+python -B -X utf8 -m pytest -q -rs -p no:cacheprovider --basetemp ./pytest-learning-queue `
+ "$repo/tests/quality/test_personal_learning_queue.py"
+```
+
+## Correct or retire a learning proposal
+
+Use the project-bound Python handle returned by `open_learning`. An existing
+D2 job can enter maintenance after a service restart. Open the item with its
+original job ID and submit a correction against the revision the user reviewed.
+
+```python
+from harnessgrad.personal.learning.maintenance_contracts import ItemRevision, MaintenanceRequest
+
+item = learning.track_job(original_job_id)
+request = MaintenanceRequest(
+ learning.scope, 'correct', (ItemRevision(item.item_id, item.revision),),
+ reason='Clarify when to run tests', idempotency_key='clarify-delivery-rule',
+ correction='- Run related tests before delivery after changing Python code.',
+)
+decision = learning.request_maintenance(request)
+if decision.status == 'needs_candidate':
+ submitted = learning.submit_maintenance_candidate(decision.decision_id)
+ report = learning.read_review(submitted.job.job_id)
+```
+
+For a proposed rule, the replacement edits the saved candidate against its
+original selected snapshot. A change to the live baseline requires a new review.
+The correction keeps its own queue job, evidence references and report. Read
+`learning.read_item_actions(item.item_id)` after reopening the service to find
+the request and its submitted job. Use `read_item_history(item.item_id)` for the
+item revisions and original job. While the worker is running, `read_review`
+returns `None` and `read_job` exposes the current status. Replaying the same
+maintenance request and decision reuses the original job.
+
+Use the same request shape with `disable` or `archive` and omit `correction` to
+retire an item. For a proposed item this records a D-side revision and preserves
+both reports. A successful text retest leaves the item proposed. Applied items
+use the existing versioned correction and rollback path. A deployment can pass
+its C3 `VersionPort` as `versions=` when opening learning. Only a matching
+application receipt can activate a correction. An installed-file rollback uses
+the C3 authorization reference and operation receipt.
+
+## Read a feedback proposal's review in the personal window
+
+Open **反馈历史 → 查看反馈与提案**. The window displays the selected feedback,
+evidence and saved native Diff. For ready proposals it can also show the original
+`AGENTS.md` from the immutable planning record, even if the project file has since
+changed. Records without the original publication can still show their saved Diff.
+
+The local B producer persists the scoped C identity in `proposal.result.evolution_job`.
+The page follows the project-scoped C job and its `comparisons/{comparison_ref}`
+resource, whose report contains both runs. The existing B `proposal.job_id`
+identifies its model budget. Opening a history entry only reads data.
+A missing C reference shows the legacy state.
+
+Receipts from a v1 provider with `result.job_ref` retain their separate report,
+run and artifact reads. The page compares the frozen snapshot and
+candidate digests to B's saved records before displaying the runs. B's SSE cursor
+and C's JSON `next_after` advance independently. After reconnection the page
+reads the job again. A refresh restores the selected project and feedback from
+this tab's session storage. A restarted service on a new origin can reopen the
+same feedback from its own history.
+
+The two run sections display each recorded attempt, command, exit code and log.
+For a v1 `retest_passed` receipt, both the page and the learning service check
+every attempt. Each baseline must miss the criterion and each candidate must
+meet it using the same command. The fixed `python-related-tests` scenario also
+requires a recorded nonzero baseline exit and a zero candidate exit. A
+contradictory pass is rejected when read. Historical receipts stay intact.
+The `python-related-tests` verdict describes instruction text. Adoption requires
+an independent scoped version receipt, discoverable through an optional
+`version_receipt_ref`. A C reply is enabled only for an open question and uses
+the scoped question ID. The local service deduplicates by question and answer.
+
+Run the focused checks from a temporary directory outside the checkout with
+`$repo` set to its absolute path:
+
+```powershell
+$env:PYTHONPATH = $repo
+$env:PYTEST_DISABLE_PLUGIN_AUTOLOAD = '1'
+$scripts = Get-ChildItem "$repo/console/static/personal-*.test.js" | ForEach-Object FullName
+node --test @scripts
+python -B -X utf8 -m pytest -q -rs -p no:cacheprovider --basetemp ./pytest-review `
+ "$repo/tests/quality/test_personal_proposal_flow.py" "$repo/tests/quality/test_personal_learning_queue.py" `
+ "$repo/tests/quality/test_personal_evolution_queue.py"
+```
diff --git a/harnessgrad/cli.py b/harnessgrad/cli.py
index fa2cdde8..605eda73 100644
--- a/harnessgrad/cli.py
+++ b/harnessgrad/cli.py
@@ -47,6 +47,7 @@
{program} personal model-config|model-demo explicit model config and offline budget demo
{program} personal plan-demo offline feedback-to-plan demo
{program} personal evolution-check offline C1 baseline or C2 comparison receipt
+ {program} personal evolution-demo feedback-to-job offline review demo
{program} version print the installed version
{program} --version the same, as a flag
diff --git a/harnessgrad/entrypoints/personal.py b/harnessgrad/entrypoints/personal.py
index c0f22c11..a66db66f 100644
--- a/harnessgrad/entrypoints/personal.py
+++ b/harnessgrad/entrypoints/personal.py
@@ -52,10 +52,10 @@ def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog='harnessgrad personal', description=__doc__)
commands = parser.add_subparsers(dest='command', required=True)
for name in ('serve', 'status', 'stop', 'project', 'import', 'demo', 'inspect', 'desktop',
- 'model-config', 'model-demo', 'plan-demo', 'evolution-check'):
+ 'model-config', 'model-demo', 'plan-demo', 'evolution-check', 'evolution-demo'):
sub = commands.add_parser(name)
sub.add_argument('--state-root', type=Path, required=name != 'model-config', help='owned directory outside the checkout')
- if name in ('project', 'demo', 'model-demo', 'plan-demo'):
+ if name in ('project', 'demo', 'model-demo', 'plan-demo', 'evolution-demo'):
sub.add_argument('--project', type=Path, required=True, help='explicit existing project; no directory scan')
if name == 'import':
sub.add_argument('--project-id', required=True)
@@ -167,6 +167,50 @@ def main(argv: list[str] | None = None) -> int:
elif args.command == 'plan-demo':
from harnessgrad.personal.fixtures import plan_demo
result = plan_demo(service, args.project)
+ elif args.command == 'evolution-demo':
+ from dataclasses import asdict
+ from harnessgrad.personal.adapters.contracts import HostBinding, TargetSelection
+ from harnessgrad.personal.contracts import SurfaceRef
+ from harnessgrad.personal.evolution_contracts import CandidateRequest, Scope
+ from harnessgrad.personal.reproduction import INSTRUCTION_RULE
+ project = service.add_project(args.project)
+ project_id = project['id']
+ feedback = service.submit_feedback({
+ 'project_id': project_id, 'kind': 'explicit_request',
+ 'text': '修改 Python 后,交付前运行相关测试', 'evidence': [],
+ 'idempotency_key': 'offline-evolution-demo', 'draft_revision': None,
+ })
+ binding = HostBinding('default', project_id, 'project', args.project.resolve(),
+ None, sys.platform, 'bypass')
+ target = TargetSelection('project-instructions', 'instruction',
+ SurfaceRef('project', 'AGENTS.md'))
+ snapshot = service.adapter.collect_selected(binding, (target,))
+ scope = Scope('default', project_id)
+ frozen = service.evolution.artifacts.register_snapshot(scope, snapshot)
+ before = snapshot.files[0].text
+ candidate = service.evolution.artifacts.register_candidate(
+ scope, frozen.ref, {'instruction.md': before + ('' if before.endswith('\n') else '\n')
+ + INSTRUCTION_RULE + '\n'},
+ )
+ job = service.evolution.submit_candidate(CandidateRequest(
+ *scope.key(), ('project-instructions',), frozen.ref, frozen.sha256,
+ candidate.ref, candidate.sha256, (feedback['id'],), 'preference',
+ ('changes Python code',), 'python-related-tests', 'offline-evolution-demo',
+ ))
+ deadline = time.monotonic() + 8
+ while time.monotonic() < deadline:
+ view = service.evolution.read_job(job)
+ if view.status in ('retest_passed', 'retest_failed', 'not_reproduced',
+ 'not_comparable', 'failed'):
+ break
+ time.sleep(.02)
+ else:
+ raise RuntimeError('offline evolution demo did not finish')
+ page = service.evolution.read_events(job, after=0)
+ result = {'fixture': True, 'feedback_id': feedback['id'], 'job': asdict(job),
+ 'view': asdict(view), 'events': asdict(page), 'applied': False,
+ 'report': (service.evolution.read_comparison(job, view.comparison_ref)
+ if view.comparison_ref else None)}
elif args.command == 'import':
result = service.import_session(args.project_id, read_import(args.input))
else:
diff --git a/harnessgrad/personal/api.py b/harnessgrad/personal/api.py
index dbb7dfc6..2a9f0514 100644
--- a/harnessgrad/personal/api.py
+++ b/harnessgrad/personal/api.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import hmac
+from dataclasses import asdict
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
@@ -16,6 +17,7 @@
from harnessgrad.personal.contracts import MAX_BYTES, decode, encode
from harnessgrad.personal.fixtures import example
from harnessgrad.personal.event_store import DraftConflict
+from harnessgrad.personal.evolution_contracts import CandidateRequest, JobRef, PortRejected
from harnessgrad.personal.feedback_store import FeedbackConflict
from harnessgrad.personal.proposal_run_store import ACTIVE, ProposalUnavailable
from harnessgrad.personal.service import PersonalService
@@ -25,6 +27,7 @@
'/personal-draft.js': ('personal-draft.js', 'text/javascript'),
'/personal-feedback.js': ('personal-feedback.js', 'text/javascript'),
'/personal-proposal.js': ('personal-proposal.js', 'text/javascript'),
+ '/personal-review.js': ('personal-review.js', 'text/javascript'),
'/personal.css': ('personal.css', 'text/css'), '/tokens.css': ('tokens.css', 'text/css')}
ASSET_ROOT = PLATFORM_ROOT / 'console' / 'static'
@@ -131,6 +134,11 @@ def dispatch(self, *, mutation=False):
self.reply(409, {'code': 'feedback_conflict', 'error': 'feedback conflicts with its saved request or draft'})
except ProposalUnavailable as error:
self.reply(409, {'code': error.code, 'error': 'proposal cannot start'})
+ except PortRejected as error:
+ status = (400 if error.reason_code in ('invalid_request', 'invalid_cursor') else
+ 404 if error.reason_code == 'out_of_scope' else
+ 409 if error.reason_code in ('idempotency_conflict', 'stale_snapshot') else 503)
+ self.reply(status, {'code': error.reason_code, 'message': 'evolution operation rejected'})
except (ValueError, KeyError, TypeError):
self.reply(400, {'error': 'invalid personal request; check selection, schema and limits'})
except (OSError, RuntimeError, sqlite3.Error):
@@ -164,6 +172,22 @@ def get(self, route, params):
return service.store.feedback.get(parts[3], parts[5])
if self.proposal_action(parts) == 'status' and not params:
return {'proposal': service.proposal(parts[3], parts[5])}
+ evolution = self.evolution_action(parts)
+ if evolution is not None:
+ project_id, job_id, action, ref = evolution
+ job = JobRef('default', project_id, job_id)
+ if action == 'status' and not params:
+ return asdict(service.evolution.read_job(job))
+ if action == 'events' and not set(params) - {'after'}:
+ raw_after = params.get('after', ['0'])[0]
+ if not raw_after.isascii() or not raw_after.isdecimal() or len(raw_after) > 19:
+ raise PortRejected('invalid_cursor')
+ return asdict(service.evolution.read_events(
+ job, after=int(raw_after)))
+ if action == 'comparison' and ref is not None and not params:
+ return service.evolution.read_comparison(job, ref)
+ if action == 'question' and ref is not None and not params:
+ return service.evolution.read_question(job, ref)
if len(parts) == 5 and parts[:3] == ['api', 'personal', 'jobs'] and parts[4] == 'events':
return {'events': service.store.job_events(parts[3], int(params.get('after', ['0'])[0]))}
raise ValueError('unknown personal route')
@@ -175,6 +199,21 @@ def proposal_action(parts):
return None
return 'status' if len(parts) == 7 else parts[7]
+ @staticmethod
+ def evolution_action(parts):
+ if (len(parts) < 6 or parts[:3] != ['api', 'personal', 'projects']
+ or parts[4] != 'evolution'):
+ return None
+ if len(parts) == 6:
+ return parts[3], parts[5], 'status', None
+ if len(parts) == 8 and parts[6] == 'comparisons':
+ return parts[3], parts[5], 'comparison', parts[7]
+ if len(parts) == 8 and parts[6] == 'questions':
+ return parts[3], parts[5], 'question', parts[7]
+ if len(parts) == 7 and parts[6] in ('events', 'reply'):
+ return parts[3], parts[5], parts[6], None
+ return None
+
def proposal_stream(self, project_id, feedback_id):
raw = self.headers.get('Last-Event-ID', '0')
if not raw.isascii() or not raw.isdecimal() or len(raw) > 19:
@@ -208,6 +247,22 @@ def post(self, route, value):
return {'proposal': service.reply_to_proposal(parts[3], parts[5], value['question_id'], value['answer'])}
if action == 'cancel' and type(value) is dict and not value:
return {'proposal': service.cancel_proposal(parts[3], parts[5])}
+ evolution = self.evolution_action(parts)
+ if evolution is not None:
+ project_id, job_id, evolution_action, _ = evolution
+ job = JobRef('default', project_id, job_id)
+ if evolution_action == 'reply' and set(value) == {'question_id', 'answer'}:
+ return asdict(service.evolution.reply(job, value['question_id'], value['answer']))
+ if (len(parts) == 5 and parts[:3] == ['api', 'personal', 'projects']
+ and parts[4] == 'evolution'):
+ if 'profile_id' in value or 'project_id' in value:
+ raise PortRejected('invalid_request')
+ try:
+ request = CandidateRequest.from_dict({**value, 'profile_id': 'default',
+ 'project_id': parts[3]})
+ except ValueError:
+ raise PortRejected('invalid_request') from None
+ return asdict(service.evolution.submit_candidate(request))
if route == '/api/personal/feedback':
return service.submit_feedback(value)
if route == '/api/personal/draft' and set(value) == {'project_id', 'text', 'revision'}:
diff --git a/harnessgrad/personal/evolution_contracts.py b/harnessgrad/personal/evolution_contracts.py
index 763be4fb..d835f4a1 100644
--- a/harnessgrad/personal/evolution_contracts.py
+++ b/harnessgrad/personal/evolution_contracts.py
@@ -55,7 +55,7 @@ def _optional_id(value: str | None) -> None:
identifier(value)
-def _bounded_texts(values: tuple[str, ...]) -> None:
+def validate_conditions(values: tuple[str, ...]) -> None:
if (not isinstance(values, tuple) or len(values) > 32
or any(not isinstance(value, str) or not value.strip()
or len(value.encode('utf-8')) > 1024 for value in values)):
@@ -138,7 +138,7 @@ def __post_init__(self):
unique_ids(self.evidence_refs)
if self.intent not in ('preference', 'behavior_fix', 'new_capability'):
raise ValueError('invalid candidate intent')
- _bounded_texts(self.conditions)
+ validate_conditions(self.conditions)
identifier(self.scenario_id)
identifier(self.idempotency_key)
diff --git a/harnessgrad/personal/evolution_queue.py b/harnessgrad/personal/evolution_queue.py
index 2a6eeed8..e0122649 100644
--- a/harnessgrad/personal/evolution_queue.py
+++ b/harnessgrad/personal/evolution_queue.py
@@ -8,9 +8,10 @@
import sqlite3
import uuid
-from harnessgrad.personal.contracts import digest, encode
+from harnessgrad.personal.contracts import decode, digest, encode, identifier
from harnessgrad.personal.evolution_contracts import (
ArtifactPort,
+ ArtifactView,
CandidateRequest,
EventPage,
JobEvent,
@@ -23,14 +24,17 @@
)
APPLICATION_ID = 0x48474331 # HarnessGrad C1
-SCHEMA_VERSION = 1
+SCHEMA_VERSION = 2
JOB_COLUMNS = (
'profile_id', 'project_id', 'id', 'idempotency_key', 'request_sha256',
'request', 'status', 'reason_code', 'candidate_id', 'question_id',
'comparison_ref',
)
EVENT_COLUMNS = ('profile_id', 'project_id', 'job_id', 'seq', 'status', 'reason_code')
-DDL = (
+ARTIFACT_COLUMNS = ('profile_id', 'project_id', 'ref', 'sha256', 'kind', 'payload')
+REPORT_COLUMNS = ('profile_id', 'project_id', 'job_id', 'ref', 'body')
+QUESTION_COLUMNS = ('profile_id', 'project_id', 'job_id', 'id', 'prompt', 'status', 'response')
+V1_DDL = (
'CREATE TABLE evolution_jobs ('
'profile_id TEXT NOT NULL, project_id TEXT NOT NULL, id TEXT NOT NULL, '
'idempotency_key TEXT NOT NULL, request_sha256 TEXT NOT NULL, request TEXT NOT NULL, '
@@ -45,6 +49,25 @@
'FOREIGN KEY(profile_id,project_id,job_id) '
'REFERENCES evolution_jobs(profile_id,project_id,id))',
)
+V2_DDL = (
+ 'CREATE TABLE evolution_artifacts ('
+ 'profile_id TEXT NOT NULL, project_id TEXT NOT NULL, ref TEXT NOT NULL, '
+ 'sha256 TEXT NOT NULL, kind TEXT NOT NULL, payload TEXT NOT NULL, '
+ 'PRIMARY KEY(profile_id,project_id,ref))',
+ 'CREATE TABLE evolution_reports ('
+ 'profile_id TEXT NOT NULL, project_id TEXT NOT NULL, job_id TEXT NOT NULL, '
+ 'ref TEXT NOT NULL, body TEXT NOT NULL, PRIMARY KEY(profile_id,project_id,job_id,ref), '
+ 'FOREIGN KEY(profile_id,project_id,job_id) '
+ 'REFERENCES evolution_jobs(profile_id,project_id,id))',
+ 'CREATE TABLE evolution_questions ('
+ 'profile_id TEXT NOT NULL, project_id TEXT NOT NULL, job_id TEXT NOT NULL, '
+ 'id TEXT NOT NULL, prompt TEXT NOT NULL, status TEXT NOT NULL '
+ "CHECK(status IN ('open','answered')), response TEXT, "
+ 'PRIMARY KEY(profile_id,project_id,job_id,id), '
+ 'FOREIGN KEY(profile_id,project_id,job_id) '
+ 'REFERENCES evolution_jobs(profile_id,project_id,id))',
+)
+DDL = V1_DDL + V2_DDL
class EvolutionQueueStore:
@@ -55,8 +78,12 @@ def __init__(self, path: Path):
with self.transaction() as db:
identity = db.execute('PRAGMA application_id').fetchone()[0]
version = db.execute('PRAGMA user_version').fetchone()[0]
- if (identity, version) == (APPLICATION_ID, SCHEMA_VERSION):
- self._require_schema(db)
+ if identity == APPLICATION_ID and version in (1, SCHEMA_VERSION):
+ self._require_schema(db, version)
+ if version == 1:
+ for statement in V2_DDL:
+ db.execute(statement)
+ db.execute(f'PRAGMA user_version={SCHEMA_VERSION}')
return
if identity or version or db.execute('SELECT 1 FROM sqlite_master LIMIT 1').fetchone():
raise ValueError('not a recognized evolution queue database')
@@ -66,8 +93,11 @@ def __init__(self, path: Path):
db.execute(f'PRAGMA user_version={SCHEMA_VERSION}')
@staticmethod
- def _require_schema(db: sqlite3.Connection) -> None:
+ def _require_schema(db: sqlite3.Connection, version: int = SCHEMA_VERSION) -> None:
expected = {'evolution_jobs': JOB_COLUMNS, 'evolution_job_events': EVENT_COLUMNS}
+ if version >= 2:
+ expected.update(evolution_artifacts=ARTIFACT_COLUMNS, evolution_reports=REPORT_COLUMNS,
+ evolution_questions=QUESTION_COLUMNS)
objects = {(row['type'], row['name']) for row in db.execute(
"SELECT type,name FROM sqlite_master WHERE name NOT GLOB 'sqlite_*'"
)}
@@ -83,6 +113,161 @@ def _require_schema(db: sqlite3.Connection) -> None:
if db.execute('PRAGMA foreign_key_check').fetchone():
raise ValueError('invalid evolution queue references')
+ def register_artifact(self, scope: Scope, artifact: ArtifactView) -> ArtifactView:
+ if not isinstance(scope, Scope) or not isinstance(artifact, ArtifactView) or artifact.truncated:
+ raise PortRejected('invalid_request')
+ body = encode(dict(artifact.payload))
+ with self.transaction() as db:
+ prior = db.execute(
+ 'SELECT sha256,kind,payload FROM evolution_artifacts '
+ 'WHERE profile_id=? AND project_id=? AND ref=?', (*scope.key(), artifact.ref),
+ ).fetchone()
+ if prior:
+ if (prior['sha256'], prior['kind'], prior['payload']) != (
+ artifact.sha256, artifact.kind, body):
+ raise PortRejected('idempotency_conflict')
+ return artifact
+ db.execute('INSERT INTO evolution_artifacts VALUES (?,?,?,?,?,?)',
+ (*scope.key(), artifact.ref, artifact.sha256, artifact.kind, body))
+ return artifact
+
+ def read_artifact(self, scope: Scope, ref: str, *, kind: str) -> ArtifactView:
+ identifier(ref); identifier(kind)
+ with closing(self.connection()) as db:
+ row = db.execute(
+ 'SELECT * FROM evolution_artifacts WHERE profile_id=? AND project_id=? AND ref=?',
+ (*scope.key(), ref),
+ ).fetchone()
+ if row is None or row['kind'] != kind:
+ raise PortRejected('out_of_scope')
+ return ArtifactView(row['ref'], row['sha256'], row['kind'], decode(row['payload']))
+
+ def read_request(self, job: JobRef) -> CandidateRequest:
+ row = self.scoped_job(job)
+ return CandidateRequest.from_dict(decode(row['request']))
+
+ def scoped_job(self, job: JobRef) -> sqlite3.Row:
+ with closing(self.connection()) as db:
+ return self._scoped_job(db, job)
+
+ @staticmethod
+ def _scoped_job(db: sqlite3.Connection, job: JobRef) -> sqlite3.Row:
+ if not isinstance(job, JobRef):
+ raise PortRejected('out_of_scope')
+ row = db.execute(
+ 'SELECT * FROM evolution_jobs WHERE profile_id=? AND project_id=? AND id=?',
+ (*job.scope.key(), job.job_id),
+ ).fetchone()
+ if row is None:
+ raise PortRejected('out_of_scope')
+ return row
+
+ def published_report(self, job: JobRef) -> dict | None:
+ """Find a v2 report committed before its terminal event by an older worker."""
+ self.scoped_job(job)
+ with closing(self.connection()) as db:
+ row = db.execute(
+ 'SELECT body FROM evolution_reports WHERE profile_id=? AND project_id=? AND job_id=? '
+ 'ORDER BY rowid LIMIT 1', (*job.scope.key(), job.job_id),
+ ).fetchone()
+ return decode(row['body']) if row else None
+
+ def read_report(self, job: JobRef, ref: str) -> dict:
+ identifier(ref)
+ self.scoped_job(job)
+ with closing(self.connection()) as db:
+ row = db.execute(
+ 'SELECT body FROM evolution_reports WHERE profile_id=? AND project_id=? AND job_id=? AND ref=?',
+ (*job.scope.key(), job.job_id, ref),
+ ).fetchone()
+ if row is None:
+ raise PortRejected('out_of_scope')
+ return decode(row['body'])
+
+ def require_answer(self, job: JobRef, question_id: str, prompt: str) -> None:
+ identifier(question_id)
+ if not isinstance(prompt, str) or not prompt.strip() or len(prompt.encode('utf-8')) > 4096:
+ raise PortRejected('invalid_request')
+ with self.transaction() as db:
+ current = self._scoped_job(db, job)
+ key = (*job.scope.key(), job.job_id, question_id)
+ if current['status'] not in ('created', 'collecting', 'needs_input'):
+ return
+ if current['status'] == 'needs_input' and current['question_id'] != question_id:
+ return
+ question = db.execute(
+ 'SELECT status FROM evolution_questions WHERE profile_id=? AND project_id=? AND job_id=? AND id=?',
+ key,
+ ).fetchone()
+ if question and question['status'] == 'answered':
+ # Repair a reply committed by an older worker before its collecting event.
+ if current['status'] == 'needs_input':
+ self._record_transition(db, JobView(job, 'collecting', candidate_id=current['candidate_id']))
+ return
+ if question is None:
+ db.execute('INSERT INTO evolution_questions VALUES (?,?,?,?,?,?,NULL)', (*key, prompt, 'open'))
+ if current['status'] != 'needs_input':
+ self._record_transition(db, JobView(job, 'needs_input', 'missing_evidence',
+ current['candidate_id'], question_id))
+
+ def read_question(self, job: JobRef, question_id: str) -> dict:
+ identifier(question_id)
+ self.scoped_job(job)
+ with closing(self.connection()) as db:
+ row = db.execute(
+ 'SELECT prompt,status FROM evolution_questions WHERE profile_id=? AND project_id=? AND job_id=? AND id=?',
+ (*job.scope.key(), job.job_id, question_id),
+ ).fetchone()
+ if row is None:
+ raise PortRejected('out_of_scope')
+ return {'job': asdict(job), 'question_id': question_id, 'prompt': row['prompt'], 'open': row['status'] == 'open'}
+
+ def answer_question(self, job: JobRef, question_id: str, answer: str) -> None:
+ identifier(question_id)
+ if not isinstance(answer, str) or not answer.strip() or len(answer.encode('utf-8')) > 16384:
+ raise PortRejected('invalid_request')
+ with self.transaction() as db:
+ current = self._scoped_job(db, job)
+ key = (*job.scope.key(), job.job_id, question_id)
+ row = db.execute(
+ 'SELECT status,response FROM evolution_questions '
+ 'WHERE profile_id=? AND project_id=? AND job_id=? AND id=?', key,
+ ).fetchone()
+ if row is None:
+ raise PortRejected('out_of_scope')
+ waiting = current['status'] == 'needs_input' and current['question_id'] == question_id
+ if row['status'] == 'answered':
+ if row['response'] != answer:
+ raise PortRejected('idempotency_conflict')
+ elif waiting:
+ db.execute(
+ "UPDATE evolution_questions SET status='answered',response=? "
+ 'WHERE profile_id=? AND project_id=? AND job_id=? AND id=?', (answer, *key),
+ )
+ else:
+ raise PortRejected('out_of_scope')
+ if waiting:
+ self._record_transition(db, JobView(job, 'collecting', candidate_id=current['candidate_id']))
+
+ @staticmethod
+ def _record_transition(db: sqlite3.Connection, view: JobView) -> None:
+ key = (*view.job.scope.key(), view.job.job_id)
+ seq = db.execute(
+ 'SELECT coalesce(max(seq),0)+1 FROM evolution_job_events '
+ 'WHERE profile_id=? AND project_id=? AND job_id=?', key,
+ ).fetchone()[0]
+ db.execute(
+ 'UPDATE evolution_jobs SET status=?,reason_code=?,question_id=?,comparison_ref=? '
+ 'WHERE profile_id=? AND project_id=? AND id=?',
+ (view.status, view.reason_code, view.question_id, view.comparison_ref, *key),
+ )
+ db.execute('INSERT INTO evolution_job_events VALUES (?,?,?,?,?,?)',
+ (*key, seq, view.status, view.reason_code))
+
+ def job_count(self) -> int:
+ with closing(self.connection()) as db:
+ return db.execute('SELECT count(*) FROM evolution_jobs').fetchone()[0]
+
def connection(self) -> sqlite3.Connection:
db = sqlite3.connect(self.path, timeout=5)
db.row_factory = sqlite3.Row
@@ -106,11 +291,13 @@ def __init__(
*,
read_evidence: Callable[[Scope, str], object],
scenario_available: Callable[[Scope, str], bool],
+ validate_selection: Callable[[CandidateRequest], None] | None = None,
):
self.store = store
self.artifacts = artifacts
self.read_evidence = read_evidence
self.scenario_available = scenario_available
+ self.validate_selection = validate_selection
@staticmethod
def _job(row: sqlite3.Row) -> JobRef:
@@ -141,9 +328,13 @@ def _validate_new(self, request: CandidateRequest) -> None:
raise PortRejected('out_of_scope') from None
if snapshot.sha256 != request.snapshot_sha256:
raise PortRejected('stale_snapshot')
- selected = snapshot.payload.get('target_ids')
- if not isinstance(selected, (list, tuple)) or tuple(selected) != request.target_ids:
- raise PortRejected('stale_snapshot')
+ if self.validate_selection is None:
+ # Original v1 providers publish the selection in the snapshot payload.
+ selected = snapshot.payload.get('target_ids')
+ if not isinstance(selected, (list, tuple)) or tuple(selected) != request.target_ids:
+ raise PortRejected('stale_snapshot')
+ else:
+ self.validate_selection(request)
if candidate.sha256 != request.candidate_sha256:
raise PortRejected('stale_snapshot')
files = candidate.payload.get('files')
@@ -155,19 +346,22 @@ def _validate_new(self, request: CandidateRequest) -> None:
if not self.scenario_available(scope, request.scenario_id):
raise PortRejected('invalid_request')
- def submit_candidate(self, request: CandidateRequest) -> JobRef:
+ def accepted_candidate(self, request: CandidateRequest) -> JobRef | None:
+ """Look up an exact prior acceptance without admitting new work."""
if not isinstance(request, CandidateRequest):
raise PortRejected('invalid_request')
- fingerprint = digest(asdict(request))
- # Check an accepted request before resolving mutable references. This
- # lets a caller recover the original receipt after a lost acknowledgement.
with closing(self.store.connection()) as db:
prior = self._prior(db, request)
if prior is not None:
- if prior['request_sha256'] != fingerprint:
+ if prior['request_sha256'] != digest(asdict(request)):
raise PortRejected('idempotency_conflict')
return self._job(prior)
+ return None
+ def submit_candidate(self, request: CandidateRequest) -> JobRef:
+ if accepted := self.accepted_candidate(request):
+ return accepted
+ fingerprint = digest(asdict(request))
self._validate_new(request)
job = JobRef(*request.scope.key(), 'evo_' + uuid.uuid4().hex)
try:
@@ -198,13 +392,7 @@ def submit_candidate(self, request: CandidateRequest) -> JobRef:
return job
def _scoped_row(self, job: JobRef) -> sqlite3.Row:
- if not isinstance(job, JobRef):
- raise PortRejected('out_of_scope')
- with closing(self.store.connection()) as db:
- row = db.execute('SELECT * FROM evolution_jobs WHERE id=?', (job.job_id,)).fetchone()
- if row is None or (row['profile_id'], row['project_id']) != job.scope.key():
- raise PortRejected('out_of_scope')
- return row
+ return self.store.scoped_job(job)
def read_job(self, job: JobRef) -> JobView:
return self._view(self._scoped_row(job))
@@ -229,21 +417,16 @@ def transition(
reason_code: str | None = None,
question_id: str | None = None,
comparison_ref: str | None = None,
+ report: dict | None = None,
) -> JobView:
- """Internal C orchestration hook used by later reproduction stages."""
- current = self._scoped_row(job)
- view = JobView(job, status, reason_code, current['candidate_id'], question_id, comparison_ref)
+ """Publish a state event and its optional comparison in one transaction."""
with self.store.transaction() as db:
- seq = db.execute(
- 'SELECT coalesce(max(seq),0)+1 FROM evolution_job_events '
- 'WHERE profile_id=? AND project_id=? AND job_id=?',
- (*job.scope.key(), job.job_id),
- ).fetchone()[0]
- db.execute(
- 'UPDATE evolution_jobs SET status=?,reason_code=?,question_id=?,comparison_ref=? '
- 'WHERE profile_id=? AND project_id=? AND id=?',
- (status, reason_code, question_id, comparison_ref, *job.scope.key(), job.job_id),
- )
- db.execute('INSERT INTO evolution_job_events VALUES (?,?,?,?,?,?)',
- (*job.scope.key(), job.job_id, seq, status, reason_code))
+ current = self.store._scoped_job(db, job)
+ view = JobView(job, status, reason_code, current['candidate_id'], question_id, comparison_ref)
+ if report is not None:
+ if comparison_ref is None or report['comparison_ref'] != comparison_ref:
+ raise ValueError('comparison reference does not match report')
+ db.execute('INSERT INTO evolution_reports VALUES (?,?,?,?,?)',
+ (*job.scope.key(), job.job_id, comparison_ref, encode(report)))
+ self.store._record_transition(db, view)
return view
diff --git a/harnessgrad/personal/evolution_service.py b/harnessgrad/personal/evolution_service.py
new file mode 100644
index 00000000..70178188
--- /dev/null
+++ b/harnessgrad/personal/evolution_service.py
@@ -0,0 +1,317 @@
+"""Personal-service assembly for frozen artifacts and offline evolution review."""
+from __future__ import annotations
+
+from collections.abc import Mapping
+from contextlib import ExitStack
+from dataclasses import asdict
+from pathlib import Path
+import sqlite3
+from threading import Event, Thread
+
+from harnessgrad.personal.adapters.contracts import PreparedExtension, SelectedSnapshot, SurfaceError
+from harnessgrad.personal.contracts import digest
+from harnessgrad.personal.evolution_contracts import (
+ ArtifactRef,
+ ArtifactView,
+ CandidateRequest,
+ EventPage,
+ JobRef,
+ JobView,
+ PortRejected,
+ Scope,
+ validate_conditions,
+)
+from harnessgrad.personal.evolution_queue import EvolutionQueue, EvolutionQueueStore
+from harnessgrad.personal.execution_lock import ExecutionLockUnavailable, execution_lock
+from harnessgrad.personal.reproduction import (
+ INSTRUCTION_REPRODUCTION,
+ INSTRUCTION_SCENARIO,
+ ReproductionScenario,
+ RunRecord,
+ ScenarioMismatch,
+ compare_runs,
+ instruction_scenario,
+ run_scenario,
+)
+
+
+RUNNABLE_STATUSES = frozenset({
+ 'created', 'collecting', 'reproducing', 'baseline_ready', 'proposing', 'validating', 'retesting',
+})
+
+
+class EvolutionArtifacts:
+ """Scoped durable artifacts; no caller supplies physical project paths."""
+
+ def __init__(self, store: EvolutionQueueStore):
+ self.store = store
+
+ def read_artifact(self, scope: Scope, ref: str, *, kind: str) -> ArtifactView:
+ return self.store.read_artifact(scope, ref, kind=kind)
+
+ def register(self, scope: Scope, artifact: ArtifactView) -> ArtifactView:
+ return self.store.register_artifact(scope, artifact)
+
+ def register_candidate(
+ self, scope: Scope, snapshot_ref: str, files: Mapping[str, str],
+ ) -> ArtifactRef:
+ self.read_artifact(scope, snapshot_ref, kind='virtual_snapshot')
+ try:
+ payload = {'files': dict(files)}
+ except (TypeError, ValueError):
+ raise PortRejected('invalid_request') from None
+ sha = digest(payload)
+ artifact = ArtifactView('candidate_' + sha, sha, 'text_candidate', payload)
+ self.register(scope, artifact)
+ return ArtifactRef(artifact.ref, artifact.sha256, artifact.kind)
+
+ def register_snapshot(self, scope: Scope, snapshot: SelectedSnapshot) -> ArtifactView:
+ if snapshot.binding.profile_id != scope.profile_id or snapshot.binding.project_id != scope.project_id:
+ raise PortRejected('out_of_scope')
+ by_surface = {(row.surface.root_id, row.surface.path): row.text for row in snapshot.files}
+ files = {row.virtual_path: by_surface[(row.surface.root_id, row.surface.path)]
+ for row in snapshot.surface_map}
+ payload = {
+ 'target_ids': [row.resource_id for row in snapshot.targets],
+ 'files': files,
+ 'selected_snapshot': snapshot.as_dict(),
+ }
+ artifact = ArtifactView('snapshot_' + snapshot.snapshot_sha256, snapshot.snapshot_sha256,
+ 'virtual_snapshot', payload)
+ return self.register(scope, artifact)
+
+
+class EvolutionWorker:
+ """Run one bounded offline comparison per durable queue job."""
+
+ def __init__(self, root: Path, queue: EvolutionQueue, *, verify_snapshot):
+ self.root = root
+ self.queue = queue
+ self.verify_snapshot = verify_snapshot
+ self._closing = Event()
+
+ def close(self) -> None:
+ self._closing.set()
+
+ def start(self, job: JobRef) -> JobView:
+ view = self.queue.read_job(job)
+ if view.status in ('created', 'collecting', 'needs_input'):
+ request = self.queue.store.read_request(job)
+ if not request.conditions:
+ self.queue.store.require_answer(
+ job, 'question_' + digest(asdict(job))[:32],
+ 'Which concrete condition should the fixed Python review scenario verify?',
+ )
+ view = self.queue.read_job(job)
+ if view.status not in RUNNABLE_STATUSES:
+ return view
+ path = self.queue.store.path.with_name('evolution-' + digest(asdict(job)) + '.lock')
+ with ExitStack() as claim:
+ try:
+ claim.enter_context(execution_lock(path, kind='evolution'))
+ except ExecutionLockUnavailable:
+ return self.queue.read_job(job)
+ # Another instance may have finished since the initial read.
+ view = self.queue.read_job(job)
+ if view.status not in RUNNABLE_STATUSES:
+ return view
+ owner = claim.pop_all()
+ try:
+ Thread(target=self._run, args=(owner, view), name='personal-evolution', daemon=True).start()
+ except RuntimeError:
+ owner.close()
+ raise
+ return self.queue.read_job(job)
+
+ def reply(self, job: JobRef, question_id: str, answer: str) -> JobView:
+ self.queue.store.answer_question(job, question_id, answer)
+ return self.start(job)
+
+ def _run(self, owner: ExitStack, view: JobView) -> None:
+ with owner:
+ self._review(view)
+
+ def _run_phase(self, job: JobRef, scenario: ReproductionScenario, phase: str) -> RunRecord:
+ # The immutable receipt lets a replacement worker reuse a completed phase.
+ ref = phase + '_' + digest(asdict(job))
+ try:
+ artifact = self.queue.store.read_artifact(job.scope, ref, kind='evolution_run')
+ except PortRejected as error:
+ if error.reason_code != 'out_of_scope':
+ raise
+ else:
+ return RunRecord(**{**artifact.payload, 'command': tuple(artifact.payload['command'])})
+ run = run_scenario(scenario, self.root, phase=phase)
+ payload = asdict(run)
+ self.queue.store.register_artifact(job.scope, ArtifactView(ref, digest(payload), 'evolution_run', payload))
+ return run
+
+ def _review(self, view: JobView) -> None:
+ job = view.job
+ try:
+ request = self.queue.store.read_request(job)
+ if view.status == 'retesting':
+ saved = self.queue.store.published_report(job)
+ if saved:
+ self.queue.transition(job, saved['status'], reason_code=saved['reason_code'],
+ comparison_ref=saved['comparison_ref'])
+ return
+ if self._closing.is_set():
+ self.queue.transition(job, 'interrupted', reason_code='service_stopping')
+ return
+ snapshot = self.queue.artifacts.read_artifact(
+ request.scope, request.snapshot_ref, kind='virtual_snapshot')
+ candidate = self.queue.artifacts.read_artifact(
+ request.scope, request.candidate_ref, kind='text_candidate')
+ if snapshot.sha256 != request.snapshot_sha256 or candidate.sha256 != request.candidate_sha256:
+ raise PortRejected('stale_snapshot')
+ self.verify_snapshot(request.scope, snapshot)
+ if request.scenario_id != INSTRUCTION_SCENARIO:
+ raise ScenarioMismatch('scenario_mismatch')
+ scenario = instruction_scenario(snapshot.payload['files'], candidate.payload['files'])
+ if view.status not in ('reproducing', 'baseline_ready', 'retesting'):
+ view = self.queue.transition(job, 'reproducing')
+ baseline = self._run_phase(job, scenario, 'baseline')
+ if view.status == 'reproducing':
+ view = self.queue.transition(job, 'baseline_ready', reason_code=baseline.reason_code)
+ if self._closing.is_set():
+ self.queue.transition(job, 'interrupted', reason_code='service_stopping')
+ return
+ if view.status != 'retesting':
+ self.queue.transition(job, 'retesting')
+ revised = self._run_phase(job, scenario, 'candidate')
+ report = compare_runs(scenario.scenario_id, baseline, revised, self.root)
+ verification_status, label = {
+ 'retest_passed': ('instruction_text_verified', '已验证指令文本'),
+ 'retest_failed': ('instruction_text_failed', '候选指令文本未满足要求'),
+ 'not_reproduced': ('baseline_passed', '原版本已满足文本要求'),
+ 'not_comparable': ('inconclusive', '指令文本复测无可比结论'),
+ }[report.status]
+ body = {
+ **asdict(report), 'job': asdict(job), 'snapshot_sha256': request.snapshot_sha256,
+ 'candidate_id': request.candidate_ref, 'candidate_sha256': request.candidate_sha256,
+ 'verification': {'status': verification_status, 'label': label,
+ 'later_behavior': 'unmeasured'},
+ }
+ self.queue.transition(job, report.status, reason_code=report.reason_code,
+ comparison_ref=report.comparison_ref, report=body)
+ except ScenarioMismatch:
+ self.queue.transition(job, 'not_comparable', reason_code='scenario_mismatch')
+ except PortRejected as error:
+ self.queue.transition(job, 'failed', reason_code=error.reason_code)
+ except (KeyError, OSError, RuntimeError, sqlite3.Error, ValueError):
+ self.queue.transition(job, 'failed', reason_code='runner_unavailable')
+
+
+class PersonalEvolution:
+ """Public personal-service use cases over the real C queue."""
+
+ def __init__(self, root: Path, feedback, adapter):
+ self.store = EvolutionQueueStore(root / 'evolution.sqlite3')
+ self.artifacts = EvolutionArtifacts(self.store)
+ self.feedback = feedback
+ self.adapter = adapter
+ self.queue = EvolutionQueue(
+ self.store, self.artifacts, read_evidence=self._read_evidence,
+ scenario_available=lambda scope, scenario: scenario == INSTRUCTION_SCENARIO,
+ )
+ self.worker = EvolutionWorker(root, self.queue, verify_snapshot=self._verify_snapshot)
+
+ def close(self) -> None:
+ self.worker.close()
+
+ def _read_evidence(self, scope: Scope, ref: str):
+ if scope.profile_id != 'default':
+ raise PortRejected('out_of_scope')
+ try:
+ return self.feedback.get(scope.project_id, ref)
+ except ValueError:
+ raise PortRejected('out_of_scope') from None
+
+ def _verify_snapshot(self, scope: Scope, artifact: ArtifactView) -> None:
+ try:
+ snapshot = SelectedSnapshot.from_dict(artifact.payload['selected_snapshot'])
+ if (snapshot.binding.profile_id, snapshot.binding.project_id) != scope.key():
+ raise PortRejected('out_of_scope')
+ self.adapter.verify_selected(snapshot.binding, snapshot)
+ except SurfaceError as error:
+ raise PortRejected(error.code) from None
+ except (KeyError, TypeError, ValueError):
+ raise PortRejected('stale_snapshot') from None
+
+ def submit_candidate(self, request: CandidateRequest) -> JobRef:
+ job = self.queue.submit_candidate(request)
+ self.worker.start(job)
+ return job
+
+ def submit_proposal(
+ self, project_id: str, feedback_id: str, snapshot: SelectedSnapshot,
+ prepared: PreparedExtension, candidate_files: Mapping[str, str], *,
+ intent: str, conditions: tuple[str, ...], reproduction: Mapping[str, str],
+ ) -> JobRef:
+ if reproduction != INSTRUCTION_REPRODUCTION:
+ raise PortRejected('scenario_unavailable')
+ try:
+ validate_conditions(conditions)
+ except ValueError:
+ raise PortRejected('invalid_conditions') from None
+ scope = Scope(snapshot.binding.profile_id, project_id)
+ if (prepared.project_id, prepared.profile_id, prepared.binding_sha256,
+ prepared.snapshot_sha256) != (
+ project_id, scope.profile_id, snapshot.binding_sha256, snapshot.snapshot_sha256):
+ raise PortRejected('stale_snapshot')
+ try:
+ submitted_files = dict(candidate_files)
+ except (TypeError, ValueError):
+ raise PortRejected('invalid_request') from None
+ baseline_by_surface = {
+ (row.surface.root_id, row.surface.path): row.text for row in snapshot.files
+ }
+ changed_by_surface = {
+ (row.surface.root_id, row.surface.path): row.after_text for row in prepared.changes
+ }
+ expected_files = {
+ row.virtual_path: changed_by_surface.get(
+ (row.surface.root_id, row.surface.path),
+ baseline_by_surface[(row.surface.root_id, row.surface.path)],
+ ) for row in snapshot.surface_map
+ }
+ if submitted_files != expected_files:
+ raise PortRejected('invalid_request')
+ frozen = self.artifacts.register_snapshot(scope, snapshot)
+ candidate = self.artifacts.register_candidate(scope, frozen.ref, submitted_files)
+ request = CandidateRequest(
+ *scope.key(), tuple(row.resource_id for row in snapshot.targets), frozen.ref,
+ frozen.sha256, candidate.ref, candidate.sha256, (feedback_id,), intent,
+ conditions, reproduction['scenario'], 'proposal_' + feedback_id,
+ )
+ return self.submit_candidate(request)
+
+ def resume_proposal(self, project_id: str, feedback_id: str, result: Mapping) -> None:
+ ref = result['evolution_job']
+ job = JobRef('default', project_id, ref['job_id'])
+ if ref != asdict(job):
+ raise PortRejected('out_of_scope')
+ request = self.store.read_request(job)
+ if (request.scope != job.scope or request.evidence_refs != (feedback_id,)
+ or request.idempotency_key != 'proposal_' + feedback_id
+ or request.snapshot_sha256 != result['snapshot_sha256']
+ or ('candidate_sha256' in result and request.candidate_sha256 != result['candidate_sha256'])
+ or self.queue.accepted_candidate(request) != job):
+ raise PortRejected('out_of_scope')
+ self.worker.start(job)
+
+ def read_job(self, job: JobRef) -> JobView:
+ return self.queue.read_job(job)
+
+ def read_events(self, job: JobRef, *, after: int) -> EventPage:
+ return self.queue.read_events(job, after=after)
+
+ def read_comparison(self, job: JobRef, ref: str) -> dict:
+ return self.store.read_report(job, ref)
+
+ def read_question(self, job: JobRef, ref: str) -> dict:
+ return self.store.read_question(job, ref)
+
+ def reply(self, job: JobRef, question_id: str, answer: str) -> JobView:
+ return self.worker.reply(job, question_id, answer)
diff --git a/harnessgrad/personal/learning/maintenance.py b/harnessgrad/personal/learning/maintenance.py
index 2d50967d..9f1a1290 100644
--- a/harnessgrad/personal/learning/maintenance.py
+++ b/harnessgrad/personal/learning/maintenance.py
@@ -1,6 +1,7 @@
"""Maintain scoped learning items while C owns version writes and authorization."""
from __future__ import annotations
+from collections.abc import Callable
from dataclasses import asdict, replace
from harnessgrad.personal.contracts import digest, encode, identifier
@@ -17,7 +18,7 @@
from harnessgrad.personal.learning.reflection_contracts import (
CandidateQueue, CandidateRequest, JobRef, PortRejected, ReflectionInput, SnapshotRef,
)
-from harnessgrad.personal.learning.reflection_store import ReflectionStore
+from harnessgrad.personal.learning.reflection_store import ReflectionRecord, ReflectionStore
from harnessgrad.personal.learning.selected_text import (
has_exact_anchor, read_snapshot_files, register_text_candidate, render_edit, whole_lines,
)
@@ -64,18 +65,39 @@ class MaintenanceService:
"""D3 entry points for item maintenance, context selection and C reconciliation."""
def __init__(self, store: LearningStore, artifacts: MaintenanceArtifacts,
- queue: CandidateQueue, versions: VersionPort):
+ queue: CandidateQueue, versions: VersionPort | None = None, *,
+ accepted_candidate: Callable[[CandidateRequest], JobRef | None] | None = None,
+ resume_candidate: Callable[[CandidateRequest, JobRef], None] | None = None):
self.items = MaintenanceStore(store)
self.reflections = ReflectionStore(store)
self.artifacts = artifacts
self.queue = queue
- self.versions = versions
+ self._versions = versions
+ self.accepted_candidate = accepted_candidate
+ self.resume_candidate = resume_candidate
+
+ @property
+ def versions(self) -> VersionPort:
+ if self._versions is None:
+ raise PortRejected('version_service_unavailable')
+ return self._versions
def track_reflection(self, request: ReflectionInput, *, legacy_text: str | None = None) -> LearningItem:
"""Import a durable D2 submission. Older proposals need an explicit, exact text anchor."""
+ return self._track(request, self.reflections.read(request), legacy_text)
+
+ def track_job(self, job: JobRef, *, legacy_text: str | None = None) -> LearningItem:
+ record = self.reflections.submitted_for_job(job)
+ if record is None or record.candidate is None or record.candidate.scope != job.scope:
+ raise PortRejected('out_of_scope')
+ candidate = record.candidate
+ snapshot = SnapshotRef(candidate.snapshot_ref, candidate.snapshot_sha256, candidate.target_ids)
+ request = ReflectionInput(job.scope, candidate.evidence_refs, snapshot, candidate.scenario_id)
+ return self._track(request, record, legacy_text)
+
+ def _track(self, request: ReflectionInput, record: ReflectionRecord | None, legacy_text: str | None) -> LearningItem:
scope = request.scope
key = 'item_' + digest([*scope.key(), self.reflections.key(request)])
- record = self.reflections.read(request)
if (record is None or record.draft is None or record.draft.experience is None
or record.draft.files is None or record.candidate is None or not _scoped(scope, record.job)):
raise PortRejected('reflection_not_submitted')
@@ -264,12 +286,18 @@ def _merge(self, scope: LearningScope, values: tuple[Revision, ...]) -> tuple[Re
def _correction(self, request: MaintenanceRequest, value: Revision) -> CandidateDraft | None:
text = request.correction
assert text is not None
- if value.item.state != 'active':
+ if value.item.state not in ('proposed', 'active'):
raise PortRejected('item_not_active')
self._check_current(request.scope, value)
if whole_lines(value.item.summary) == whole_lines(text):
return None
- snapshot, files = self._freeze(request.scope, value)
+ if value.item.state == 'proposed':
+ candidate = value.candidate
+ snapshot = SnapshotRef(candidate.snapshot_ref, candidate.snapshot_sha256, candidate.target_ids)
+ baseline = read_snapshot_files(self.artifacts, request.scope, snapshot)
+ files = self._candidate_files(request.scope, candidate, baseline)
+ else:
+ snapshot, files = self._freeze(request.scope, value)
if value.path not in files:
raise PortRejected('stale_snapshot')
old = _anchor(files[value.path], value.item.summary)
@@ -283,19 +311,26 @@ def _correction(self, request: MaintenanceRequest, value: Revision) -> Candidate
raise PortRejected('invalid_correction') from exc
return CandidateDraft(snapshot, updated)
- def _restore_candidate(self, scope: LearningScope, value: Revision) -> CandidateDraft:
- if value.merged_into is not None:
- raise PortRejected('merged_item')
- snapshot, files = self._freeze(scope, value)
- candidate = value.candidate
+ def _candidate_files(
+ self, scope: LearningScope, candidate: CandidateRequest, baseline: dict[str, str],
+ ) -> dict[str, str]:
artifact = self.artifacts.read_artifact(scope, candidate.candidate_ref, kind='text_candidate')
if (artifact.ref != candidate.candidate_ref or artifact.kind != 'text_candidate' or artifact.truncated
or artifact.sha256 != candidate.candidate_sha256 or set(artifact.payload) != {'files'}
or digest(artifact.payload) != candidate.candidate_sha256):
raise PortRejected('invalid_candidate_artifact')
- restored = artifact.payload['files']
- if (not isinstance(restored, dict) or restored.keys() != files.keys()
- or {path for path in files if restored[path] != files[path]} != {value.path}):
+ files = artifact.payload['files']
+ if (not isinstance(files, dict) or files.keys() != baseline.keys()
+ or any(not isinstance(text, str) for text in files.values())):
+ raise PortRejected('invalid_candidate_artifact')
+ return files
+
+ def _restore_candidate(self, scope: LearningScope, value: Revision) -> CandidateDraft:
+ if value.merged_into is not None:
+ raise PortRejected('merged_item')
+ snapshot, files = self._freeze(scope, value)
+ restored = self._candidate_files(scope, value.candidate, files)
+ if {path for path in files if restored[path] != files[path]} != {value.path}:
raise PortRejected('restore_requires_review')
_anchor(restored[value.path], value.item.summary)
return CandidateDraft(snapshot, dict(restored))
@@ -327,13 +362,21 @@ def submit_candidate(self, scope: LearningScope, decision_id: str) -> Maintenanc
with self.items.lock(scope):
record = self._action(scope, decision_id, 'needs_candidate')
if record.decision.job is not None:
+ if self.resume_candidate is not None:
+ if record.decision.candidate is None:
+ raise PortRejected('invalid_maintenance_decision')
+ self.resume_candidate(record.decision.candidate, record.decision.job)
return record.decision
decision = self._prepare_candidate(record)
- saved = self._subject(record)
assert decision.candidate is not None
- self._begin_dispatch(record, saved, decision.candidate)
+ # A retirement may have advanced the item after C accepted the job but
+ # before D saved its acknowledgement. Only replay that exact admission.
+ accepted = (self.accepted_candidate(decision.candidate)
+ if record.dispatch_sha256 is not None and self.accepted_candidate else None)
+ if accepted is None:
+ self._begin_dispatch(record, self._subject(record), decision.candidate)
job = self.queue.submit_candidate(decision.candidate)
- if not _scoped(scope, job):
+ if not _scoped(scope, job) or (accepted is not None and accepted != job):
raise PortRejected('out_of_scope')
self.items.record_result(record, 'job_id', identifier(job.job_id))
return replace(decision, job=job)
@@ -442,16 +485,18 @@ def _applied(
if (record is None or record.request.items[0].item_id != value.item.item_id
or record.revision != value.item.revision or record.decision.candidate is None):
raise PortRejected('stale_operation')
- if record.request.action == 'correct' and value.item.state == 'active':
+ if record.request.action == 'correct' and value.item.state in ('active', 'proposed'):
assert record.request.correction is not None
text = record.request.correction
elif not (record.request.action == 'restore' and value.rolled_back):
raise PortRejected('stale_operation')
- self._check_binding(scope, value)
+ if value.item.state != 'proposed':
+ self._check_binding(scope, value)
candidate = record.decision.candidate
receipt, versions = self._receipt(scope, value, op, ref, 'applied',
- expected_before=None if existing_submission else value.versions)
- if receipt.candidate_sha256 != candidate.candidate_sha256:
+ expected_before=None if value.item.state == 'proposed' else value.versions)
+ if (receipt.candidate_sha256 != candidate.candidate_sha256
+ or receipt.candidate_id is not None and receipt.candidate_id != candidate.candidate_ref):
raise PortRejected('candidate_mismatch')
return replace(value.next(state='active', summary=text, job=op.job, version_receipt_ref=receipt.receipt_ref),
candidate=candidate, versions=versions, receipt=receipt,
@@ -510,6 +555,12 @@ def _operation(self, reference: OperationRef) -> OperationView:
return view
def _check_current(self, scope: LearningScope, value: Revision) -> None:
+ if value.item.state == 'proposed' and value.receipt is None and not value.versions:
+ selected = self.artifacts.freeze_snapshot(scope, value.item.target_ids)
+ if (selected.target_ids != value.candidate.target_ids
+ or selected.snapshot_sha256 != value.candidate.snapshot_sha256):
+ raise PortRejected('stale_snapshot')
+ return
self._check_binding(scope, value)
if self._current(scope, value.item.target_ids) != value.versions:
raise PortRejected('version_conflict')
diff --git a/harnessgrad/personal/learning/maintenance_contracts.py b/harnessgrad/personal/learning/maintenance_contracts.py
index 412e0e56..8b5e0461 100644
--- a/harnessgrad/personal/learning/maintenance_contracts.py
+++ b/harnessgrad/personal/learning/maintenance_contracts.py
@@ -98,6 +98,12 @@ class MaintenanceDecision:
reason_code: str | None = None
+@dataclass(frozen=True)
+class MaintenanceEntry:
+ request: MaintenanceRequest
+ decision: MaintenanceDecision
+
+
@dataclass(frozen=True)
class CurrentVersion:
target_id: str
diff --git a/harnessgrad/personal/learning/maintenance_store.py b/harnessgrad/personal/learning/maintenance_store.py
index 1e283f93..3adac7d3 100644
--- a/harnessgrad/personal/learning/maintenance_store.py
+++ b/harnessgrad/personal/learning/maintenance_store.py
@@ -5,11 +5,11 @@
from dataclasses import asdict, dataclass, replace
import sqlite3
-from harnessgrad.personal.contracts import MAX_BYTES, decode, digest, encode
+from harnessgrad.personal.contracts import MAX_BYTES, decode, digest, encode, identifier
from harnessgrad.personal.execution_lock import execution_lock
from harnessgrad.personal.learning.contracts import LearningScope
from harnessgrad.personal.learning.maintenance_contracts import (
- CurrentVersion, ItemRevision, LearningItem, MaintenanceDecision, MaintenanceRequest,
+ CurrentVersion, ItemRevision, LearningItem, MaintenanceDecision, MaintenanceEntry, MaintenanceRequest,
OperationRef, VersionEntry, VersionReceipt,
)
from harnessgrad.personal.learning.reflection_contracts import CandidateRequest, JobRef, SnapshotRef
@@ -173,6 +173,13 @@ def rollbacks(self, scope: LearningScope, item_id: str) -> tuple[MaintenanceReco
actions = tuple(MaintenanceRecord.from_row(row) for row in rows)
return tuple(record for record in actions if record.decision.status == 'needs_rollback')
+ def item_actions(self, scope: LearningScope, item_id: str) -> tuple[MaintenanceEntry, ...]:
+ with closing(self.store.connection()) as db:
+ rows = db.execute(f'SELECT * FROM maintenance_decisions WHERE {SCOPE} AND item_id=? ORDER BY rowid',
+ (*scope.key(), identifier(item_id)))
+ records = (MaintenanceRecord.from_row(row) for row in rows)
+ return tuple(MaintenanceEntry(record.request, record.decision) for record in records)
+
def save_action(self, record: MaintenanceRecord, updates: tuple[Revision, ...] = ()) -> None:
request = record.request
body = encode(asdict(record))
diff --git a/harnessgrad/personal/learning/reflection.py b/harnessgrad/personal/learning/reflection.py
index 99eeb519..c4e5bf95 100644
--- a/harnessgrad/personal/learning/reflection.py
+++ b/harnessgrad/personal/learning/reflection.py
@@ -13,6 +13,7 @@
CandidateRequest,
ExistingExperience,
Experience,
+ JobRef,
LearningDecision,
PortRejected,
ReflectionInput,
@@ -118,29 +119,32 @@ def _deferred(reason: str) -> ReflectionReceipt:
return ReflectionReceipt(LearningDecision('deferred', reason_code=reason))
-def _saved_receipt(record: ReflectionRecord | None, *, enqueue: bool) -> ReflectionReceipt | None:
- if record is None or record.draft is None:
- return None
- draft = record.draft
- if draft.status != 'candidate_ready':
- return ReflectionReceipt(LearningDecision(draft.status, reason_code=draft.reason_code))
- if record.candidate is not None and (record.job is not None or not enqueue):
- return ReflectionReceipt(LearningDecision('candidate_ready', record.candidate), draft.experience, record.job)
- return None
-
-
class ReflectionService:
"""D2 orchestration. ModelSession-compatible JSON callbacks are injected by the caller."""
def __init__(self, store: LearningStore, artifacts: ArtifactPort, queue: CandidateQueue, *,
ask: Callable[[str], dict],
- read_existing: Callable[[LearningScope, SnapshotRef], tuple[ExistingExperience, ...]]):
+ read_existing: Callable[[LearningScope, SnapshotRef], tuple[ExistingExperience, ...]],
+ resume_candidate: Callable[[CandidateRequest, JobRef], None] | None = None):
self.store = store
self.reflections = ReflectionStore(store)
self.artifacts = artifacts
self.queue = queue
self.ask = ask
self.read_existing = read_existing
+ self.resume_candidate = resume_candidate
+
+ def _saved_receipt(self, record: ReflectionRecord | None, *, enqueue: bool) -> ReflectionReceipt | None:
+ if record is None or record.draft is None:
+ return None
+ draft = record.draft
+ if draft.status != 'candidate_ready':
+ return ReflectionReceipt(LearningDecision(draft.status, reason_code=draft.reason_code))
+ if record.candidate is not None and (record.job is not None or not enqueue):
+ if enqueue and record.job is not None and self.resume_candidate is not None:
+ self.resume_candidate(record.candidate, record.job)
+ return ReflectionReceipt(LearningDecision('candidate_ready', record.candidate), draft.experience, record.job)
+ return None
def reflect(self, request: ReflectionInput) -> LearningDecision:
return self._run(request, enqueue=False).decision
@@ -165,7 +169,7 @@ def _submit(self, request: ReflectionInput, prepared: ReflectionReceipt) -> Refl
def _run(self, request: ReflectionInput, *, enqueue: bool) -> ReflectionReceipt:
try:
self.store.read_reflection_evidence(request.scope, request.evidence_refs)
- if receipt := _saved_receipt(self.reflections.read(request), enqueue=enqueue):
+ if receipt := self._saved_receipt(self.reflections.read(request), enqueue=enqueue):
return receipt
with self.reflections.lock(request):
record = self.reflections.read(request)
@@ -175,7 +179,7 @@ def _run(self, request: ReflectionInput, *, enqueue: bool) -> ReflectionReceipt:
if record is not None and record.call_started else self._generate(request))
self.reflections.save_draft(request, draft)
record = ReflectionRecord(draft=draft)
- if receipt := _saved_receipt(record, enqueue=enqueue):
+ if receipt := self._saved_receipt(record, enqueue=enqueue):
return receipt
assert record.draft is not None
candidate = record.candidate or self._register(request, record.draft)
diff --git a/harnessgrad/personal/learning/reflection_store.py b/harnessgrad/personal/learning/reflection_store.py
index 9085146c..47ffd71a 100644
--- a/harnessgrad/personal/learning/reflection_store.py
+++ b/harnessgrad/personal/learning/reflection_store.py
@@ -7,6 +7,7 @@
from harnessgrad.personal.contracts import decode, digest, encode
from harnessgrad.personal.execution_lock import execution_lock
+from harnessgrad.personal.evolution_contracts import Scope
from harnessgrad.personal.learning.reflection_contracts import (
CandidateRequest,
Experience,
@@ -45,6 +46,15 @@ class ReflectionRecord:
job: JobRef | None = None
call_started: bool = False
+ @classmethod
+ def from_row(cls, row: sqlite3.Row) -> ReflectionRecord:
+ return cls(
+ ReflectionDraft.from_json(row['draft']) if row['draft'] is not None else None,
+ CandidateRequest.from_dict(decode(row['candidate'])) if row['candidate'] is not None else None,
+ JobRef(row['profile_id'], row['project_id'], row['job_id']) if row['job_id'] is not None else None,
+ call_started=row['call_started'] is not None,
+ )
+
class ReflectionStore:
def __init__(self, store: LearningStore):
@@ -52,7 +62,30 @@ def __init__(self, store: LearningStore):
@staticmethod
def key(request: ReflectionInput) -> str:
- return 'd2_' + digest([*request.scope.key(), request.evidence_refs])
+ return ReflectionStore._evidence_key(request.scope, request.evidence_refs)
+
+ @staticmethod
+ def _evidence_key(scope: Scope, evidence_refs: tuple[str, ...]) -> str:
+ return 'd2_' + digest([*scope.key(), evidence_refs])
+
+ def frozen_candidate(self, scope: Scope, evidence_refs: tuple[str, ...]) -> CandidateRequest | None:
+ """Find the exact published request even if the live project has since changed."""
+ with closing(self.store.connection()) as db:
+ row = db.execute(f'SELECT candidate FROM reflections WHERE {SCOPE} AND id=?',
+ (*scope.key(), self._evidence_key(scope, evidence_refs))).fetchone()
+ return CandidateRequest.from_dict(decode(row['candidate'])) if row and row['candidate'] else None
+
+ def candidate_for_job(self, job: JobRef) -> CandidateRequest | None:
+ with closing(self.store.connection()) as db:
+ row = db.execute(f'SELECT candidate FROM reflections WHERE {SCOPE} AND job_id=?',
+ (*job.scope.key(), job.job_id)).fetchone()
+ return CandidateRequest.from_dict(decode(row['candidate'])) if row and row['candidate'] else None
+
+ def submitted_for_job(self, job: JobRef) -> ReflectionRecord | None:
+ with closing(self.store.connection()) as db:
+ row = db.execute(f'SELECT * FROM reflections WHERE {SCOPE} AND job_id=?',
+ (*job.scope.key(), job.job_id)).fetchone()
+ return ReflectionRecord.from_row(row) if row else None
def lock(self, request: ReflectionInput):
database = self.store.path.resolve()
@@ -70,14 +103,7 @@ def _row(self, db: sqlite3.Connection, request: ReflectionInput) -> sqlite3.Row
def read(self, request: ReflectionInput) -> ReflectionRecord | None:
with closing(self.store.connection()) as db:
row = self._row(db, request)
- if row is None:
- return None
- return ReflectionRecord(
- ReflectionDraft.from_json(row['draft']) if row['draft'] is not None else None,
- CandidateRequest.from_dict(decode(row['candidate'])) if row['candidate'] is not None else None,
- JobRef(*request.scope.key(), row['job_id']) if row['job_id'] is not None else None,
- call_started=row['call_started'] is not None,
- )
+ return ReflectionRecord.from_row(row) if row else None
def claim(self, request: ReflectionInput) -> tuple[dict, ...]:
scope = request.scope.key()
diff --git a/harnessgrad/personal/learning/submissions.py b/harnessgrad/personal/learning/submissions.py
new file mode 100644
index 00000000..4bad3b0a
--- /dev/null
+++ b/harnessgrad/personal/learning/submissions.py
@@ -0,0 +1,212 @@
+"""Submit one saved learning decision and follow its scoped evolution receipts."""
+from __future__ import annotations
+
+from collections.abc import Callable
+from dataclasses import asdict, dataclass
+from typing import Protocol
+
+from harnessgrad.personal.evolution_contracts import (
+ CandidateRequest, EventPage, EvolutionQueuePort, JobRef, JobView, PortRejected, Scope, event_cursor,
+)
+from harnessgrad.personal.learning.extension_contracts import ComparisonReport, RunRecord
+from harnessgrad.personal.learning.maintenance import MaintenanceService
+from harnessgrad.personal.learning.maintenance_contracts import (
+ LearningItem, MaintenanceArtifacts, MaintenanceDecision, MaintenanceEntry, MaintenanceRequest, OperationRef,
+ TaskContext,
+)
+from harnessgrad.personal.learning.reflection import ReflectionService
+from harnessgrad.personal.learning.reflection_contracts import (
+ LearningDecision, ReflectionInput, ReflectionReceipt, SnapshotRef,
+)
+from harnessgrad.personal.learning.service import LearningService
+from harnessgrad.personal.learning.store import EvidenceUnavailable
+
+SCENARIO_ID = 'python-related-tests'
+
+
+def _supports_retest_pass(run: RunRecord) -> bool:
+ candidate = run.phase == 'candidate'
+ if run.judge_result != ('met' if candidate else 'not_met'):
+ return False
+ if run.scenario_id != SCENARIO_ID:
+ return True
+ return type(run.exit_code) is int and (run.exit_code == 0) == candidate
+
+
+class ReviewReader(Protocol):
+ def read_comparison(self, job: JobRef, report_ref: str) -> ComparisonReport: ...
+ def read_run(self, job: JobRef, run_ref: str) -> RunRecord: ...
+
+
+@dataclass(frozen=True)
+class LearningReview:
+ report: ComparisonReport
+ baseline: tuple[RunRecord, ...]
+ candidate: tuple[RunRecord, ...]
+
+
+class LearningSubmissions:
+ def __init__(self, scope: Scope, intake: LearningService, reflection: ReflectionService,
+ artifacts: MaintenanceArtifacts, queue: EvolutionQueuePort, reports: ReviewReader | None,
+ *, local_comparison: Callable[[JobRef, str], dict] | None = None,
+ maintenance: MaintenanceService | None = None):
+ self.scope = scope
+ self.intake = intake
+ self.reflection = reflection
+ self.artifacts = artifacts
+ self.queue = queue
+ self.reports = reports
+ self.local_comparison = local_comparison
+ self._maintenance = maintenance or MaintenanceService(intake.store, artifacts, queue)
+
+ def submit_decision(self, seq: int) -> ReflectionReceipt:
+ """A durable decision sequence remains usable after the source cursor advances."""
+ if event_cursor(seq) == 0:
+ raise PortRejected('invalid_cursor')
+ rows = self.intake.store.read_receipts(self.scope, after=seq - 1, limit=1)
+ if not rows or rows[0].seq != seq:
+ raise PortRejected('out_of_scope')
+ decision = rows[0].decision
+ if decision.status != 'triggered':
+ return ReflectionReceipt(LearningDecision('deferred', reason_code='evidence_not_triggered'))
+ try:
+ self.intake.store.read_reflection_evidence(self.scope, decision.evidence_refs)
+ prior = self.reflection.reflections.frozen_candidate(self.scope, decision.evidence_refs)
+ if prior is None:
+ snapshot = self.artifacts.freeze_snapshot(self.scope, ('project-instructions',))
+ else:
+ snapshot = SnapshotRef(prior.snapshot_ref, prior.snapshot_sha256, prior.target_ids)
+ request = ReflectionInput(self.scope, decision.evidence_refs, snapshot, SCENARIO_ID)
+ return self.reflection.submit(request)
+ except EvidenceUnavailable as error:
+ return ReflectionReceipt(LearningDecision('deferred', reason_code=str(error)))
+ except PortRejected as error:
+ return ReflectionReceipt(LearningDecision('deferred', reason_code=error.reason_code))
+
+ def track_job(self, job_id: str, *, legacy_text: str | None = None) -> LearningItem:
+ """Open an acknowledged D2 submission for maintenance without repeating reflection."""
+ return self._maintenance.track_job(JobRef(*self.scope.key(), job_id), legacy_text=legacy_text)
+
+ def request_maintenance(self, request: MaintenanceRequest) -> MaintenanceDecision:
+ if request.scope != self.scope:
+ raise PortRejected('out_of_scope')
+ return self._maintenance.request_maintenance(request)
+
+ def submit_maintenance_candidate(self, decision_id: str) -> MaintenanceDecision:
+ return self._maintenance.submit_candidate(self.scope, decision_id)
+
+ def read_item_history(self, item_id: str) -> tuple[LearningItem, ...]:
+ return self._maintenance.read_history(self.scope, item_id)
+
+ def read_item_actions(self, item_id: str) -> tuple[MaintenanceEntry, ...]:
+ return self._maintenance.items.item_actions(self.scope, item_id)
+
+ def select_context(self, context: TaskContext) -> tuple[LearningItem, ...]:
+ return self._maintenance.select_context(self.scope, context)
+
+ def request_rollback(self, decision_id: str, authorization_ref: str) -> OperationRef:
+ return self._maintenance.request_rollback(self.scope, decision_id, authorization_ref)
+
+ def reconcile_learning_item(self, item_id: str, operation: OperationRef) -> LearningItem:
+ return self._maintenance.reconcile_learning_item(self.scope, item_id, operation)
+
+ def _candidate_for_job(self, job: JobRef) -> CandidateRequest | None:
+ candidate = self.reflection.reflections.candidate_for_job(job)
+ if candidate is not None:
+ return candidate
+ record = self._maintenance.items.action(self.scope, 'job_id', job.job_id)
+ return record.decision.candidate if record and record.decision.job == job else None
+
+ def read_job(self, job_id: str) -> JobView:
+ job = JobRef(*self.scope.key(), job_id)
+ view = self.queue.read_job(job)
+ if view.job != job:
+ raise PortRejected('out_of_scope')
+ return view
+
+ def read_events(self, job_id: str, *, after: int) -> EventPage:
+ job = JobRef(*self.scope.key(), job_id)
+ page = self.queue.read_events(job, after=event_cursor(after))
+ if any(event.job != job for event in page.events):
+ raise PortRejected('out_of_scope')
+ if (page.events and page.events[0].seq <= after) or (not page.events and page.next_after != after):
+ raise PortRejected('invalid_cursor')
+ return page
+
+ def _read_local_review(self, view: JobView) -> dict:
+ if self.local_comparison is None:
+ raise PortRejected('unavailable')
+ report = self.local_comparison(view.job, view.comparison_ref)
+ if report.get('job') != asdict(view.job) or report.get('comparison_ref') != view.comparison_ref:
+ raise PortRejected('out_of_scope')
+ frozen = self._candidate_for_job(view.job)
+ if (not frozen or frozen.scope != view.job.scope or report.get('candidate_id') != view.candidate_id
+ or view.candidate_id != frozen.candidate_ref
+ or report.get('candidate_sha256') != frozen.candidate_sha256
+ or report.get('snapshot_sha256') != frozen.snapshot_sha256
+ or report.get('scenario_id') != frozen.scenario_id or report.get('status') != view.status):
+ raise PortRejected('invalid_comparison_report')
+ for phase in ('baseline', 'candidate'):
+ run = report.get(phase)
+ if (not isinstance(run, dict) or run.get('phase') != phase or not run.get('run_ref')
+ or run.get('scenario_id') != frozen.scenario_id):
+ raise PortRejected('invalid_run_receipt')
+ baseline, candidate = report['baseline'], report['candidate']
+ if baseline['run_ref'] == candidate['run_ref'] or (view.status == 'retest_passed' and (
+ report.get('comparable') is not True or not baseline.get('command')
+ or baseline['command'] != candidate.get('command')
+ or any(run.get('source_unchanged') is not True or run.get('timed_out') is not False
+ or run.get('reason_code') or type(run.get('exit_code')) is not int
+ for run in (baseline, candidate))
+ or baseline['exit_code'] == 0 or candidate['exit_code'] != 0)):
+ raise PortRejected('invalid_comparison_report')
+ return report
+
+ def read_review(self, job_id: str) -> LearningReview | dict | None:
+ view = self.read_job(job_id)
+ if view.comparison_ref is None:
+ return None
+ if self.reports is None:
+ return self._read_local_review(view)
+ job = view.job
+ report = self.reports.read_comparison(job, view.comparison_ref)
+ if (report.report_ref, report.job) != (view.comparison_ref, job):
+ raise PortRejected('out_of_scope')
+ if (report.candidate_id is not None and report.candidate_id != view.candidate_id
+ or report.verdict != view.status):
+ raise PortRejected('invalid_comparison_report')
+ refs = report.baseline_run_refs + report.candidate_run_refs
+ if len(set(refs)) != len(refs):
+ raise PortRejected('invalid_comparison_report')
+ frozen = self._candidate_for_job(job)
+ if (frozen is None or frozen.scope != job.scope or view.candidate_id != frozen.candidate_ref
+ or report.candidate_sha256 is not None and report.candidate_sha256 != frozen.candidate_sha256):
+ raise PortRejected('invalid_comparison_report')
+
+ def runs(refs: tuple[str, ...], phase: str) -> tuple[RunRecord, ...]:
+ result = []
+ for ref in refs:
+ run = self.reports.read_run(job, ref)
+ if (run.job, run.run_ref) != (job, ref):
+ raise PortRejected('out_of_scope')
+ if run.phase != phase or run.fixture != report.fixture:
+ raise PortRejected('invalid_run_receipt')
+ if (run.scenario_id, run.snapshot_sha256) != (frozen.scenario_id, frozen.snapshot_sha256):
+ raise PortRejected('invalid_run_receipt')
+ result.append(run)
+ return tuple(result)
+
+ baseline = runs(report.baseline_run_refs, 'baseline')
+ candidate = runs(report.candidate_run_refs, 'candidate')
+ if any(run.prepared_sha256 != report.candidate_sha256 for run in candidate):
+ raise PortRejected('invalid_comparison_report')
+ if report.verdict == 'retest_passed' and (
+ not report.comparable or not report.candidate_id or not report.candidate_sha256
+ or not baseline or not candidate or 'execution_timeout' in (view.reason_code, report.reason_code)
+ or any(run.status != 'executed' or run.reason_code == 'execution_timeout'
+ or not _supports_retest_pass(run) or not run.command or run.command != baseline[0].command
+ for run in (*baseline, *candidate))
+ or len({(run.scenario_id, run.scenario_sha256, run.snapshot_sha256)
+ for run in (*baseline, *candidate)}) != 1):
+ raise PortRejected('invalid_comparison_report')
+ return LearningReview(report, baseline, candidate)
diff --git a/harnessgrad/personal/learning_artifacts.py b/harnessgrad/personal/learning_artifacts.py
new file mode 100644
index 00000000..4924f6b5
--- /dev/null
+++ b/harnessgrad/personal/learning_artifacts.py
@@ -0,0 +1,126 @@
+"""Local immutable instruction artifacts backed by the selected Codex project."""
+from __future__ import annotations
+
+from collections.abc import Mapping
+from pathlib import Path
+
+from harnessgrad.personal import records
+from harnessgrad.personal.adapters.codex import CodexAdapter
+from harnessgrad.personal.adapters.contracts import HostBinding, SelectedSnapshot, SurfaceError, TargetSelection
+from harnessgrad.personal.contracts import SurfaceRef, digest
+from harnessgrad.personal.evolution_contracts import (
+ ArtifactRef, ArtifactView, CandidateRequest, JobRef, PortRejected, Scope, SnapshotRef,
+)
+from harnessgrad.personal.evolution_queue import EvolutionQueue
+from harnessgrad.personal.evolution_service import RUNNABLE_STATUSES, EvolutionArtifacts, PersonalEvolution
+
+INSTRUCTION_TARGET = 'project-instructions'
+
+
+class ProjectLearningArtifacts:
+ """Only the root AGENTS.md of the service-registered binding is exposed."""
+
+ def __init__(self, root: Path, binding: HostBinding, adapter: CodexAdapter):
+ self.binding = binding
+ self.scope = Scope(binding.profile_id, binding.project_id)
+ self.root = root / digest(self.scope.key())
+ self.adapter = adapter
+
+ def _require_scope(self, scope: Scope) -> None:
+ if scope != self.scope:
+ raise PortRejected('out_of_scope')
+
+ def _read(self, kind: str, ref: str) -> dict:
+ try:
+ return records.read(self.root / kind, ref)
+ except (ValueError, OSError):
+ raise PortRejected('out_of_scope') from None
+
+ def _snapshot(self, ref: str) -> SelectedSnapshot:
+ return SelectedSnapshot.from_dict(self._read('virtual_snapshot', ref))
+
+ def freeze_snapshot(self, scope: Scope, target_ids: tuple[str, ...]) -> SnapshotRef:
+ self._require_scope(scope)
+ if target_ids != (INSTRUCTION_TARGET,):
+ raise PortRejected('out_of_scope')
+ target = TargetSelection(INSTRUCTION_TARGET, 'instruction', SurfaceRef(self.binding.root_id, 'AGENTS.md'))
+ try:
+ snapshot = self.adapter.collect_selected(self.binding, (target,))
+ except SurfaceError as error:
+ raise PortRejected(error.code) from None
+ ref = records.write(self.root / 'virtual_snapshot', snapshot.as_dict())
+ return SnapshotRef(ref, snapshot.snapshot_sha256, target_ids)
+
+ def register_candidate(self, scope: Scope, snapshot_ref: str, files: Mapping[str, str]) -> ArtifactRef:
+ self._require_scope(scope)
+ snapshot = self._snapshot(snapshot_ref)
+ try:
+ self.adapter.prepare_extension(snapshot, files)
+ except SurfaceError as error:
+ raise PortRejected(error.code) from None
+ payload = {'files': dict(files)}
+ ref = records.write(self.root / 'text_candidate', {'snapshot_ref': snapshot_ref, 'payload': payload})
+ return ArtifactRef(ref, digest(payload), 'text_candidate')
+
+ def read_artifact(self, scope: Scope, ref: str, *, kind: str) -> ArtifactView:
+ self._require_scope(scope)
+ if kind == 'virtual_snapshot':
+ snapshot = self._snapshot(ref)
+ file, = snapshot.files
+ return ArtifactView(ref, snapshot.snapshot_sha256, kind, {'files': {'instruction.md': file.text}})
+ if kind == 'text_candidate':
+ payload = self._read(kind, ref)['payload']
+ return ArtifactView(ref, digest(payload), kind, payload)
+ raise PortRejected('out_of_scope')
+
+ def validate_selection(self, request: CandidateRequest) -> None:
+ self._require_scope(request.scope)
+ snapshot = self._snapshot(request.snapshot_ref)
+ candidate = self._read('text_candidate', request.candidate_ref)
+ if (request.target_ids != tuple(target.resource_id for target in snapshot.targets)
+ or candidate['snapshot_ref'] != request.snapshot_ref):
+ raise PortRejected('stale_snapshot')
+ try:
+ self.adapter.verify_selected(self.binding, snapshot)
+ except SurfaceError as error:
+ raise PortRejected(error.code) from None
+
+ def publish(self, request: CandidateRequest, registry: EvolutionArtifacts) -> None:
+ """Keep frozen D identities on C's side, including requests prepared before C2."""
+ scope = request.scope
+ self._require_scope(scope)
+ selected = self._snapshot(request.snapshot_ref)
+ snapshot = self.read_artifact(scope, request.snapshot_ref, kind='virtual_snapshot')
+ candidate = self.read_artifact(scope, request.candidate_ref, kind='text_candidate')
+ payload = {**snapshot.payload, 'target_ids': [row.resource_id for row in selected.targets],
+ 'selected_snapshot': selected.as_dict()}
+ registry.register(scope, ArtifactView(snapshot.ref, snapshot.sha256, snapshot.kind, payload))
+ registry.register(scope, candidate)
+
+
+class LearningEvolutionQueue(EvolutionQueue):
+ """D uses its scoped evidence reader at admission and C's shared worker after acceptance."""
+
+ def __init__(self, evolution: PersonalEvolution, artifacts, *, read_evidence, scenario_available):
+ super().__init__(evolution.store, artifacts, read_evidence=read_evidence,
+ scenario_available=scenario_available, validate_selection=artifacts.validate_selection)
+ self.evolution = evolution
+
+ def resume_candidate(self, request: CandidateRequest, job: JobRef) -> None:
+ """Recover an existing acknowledgement without authorizing a new admission."""
+ if job.scope != request.scope or self.accepted_candidate(request) != job:
+ raise PortRejected('out_of_scope')
+ if self.read_job(job).status in RUNNABLE_STATUSES:
+ # Jobs accepted by the v1 queue may only have D's original frozen records.
+ self.artifacts.publish(request, self.evolution.artifacts)
+ self.evolution.worker.start(job)
+
+ def submit_candidate(self, request: CandidateRequest) -> JobRef:
+ if not isinstance(request, CandidateRequest):
+ raise PortRejected('invalid_request')
+ # Freeze the worker's inputs before the job becomes visible. The same records
+ # also hydrate old D-only acceptances without rereading the live project.
+ self.artifacts.publish(request, self.evolution.artifacts)
+ job = super().submit_candidate(request)
+ self.evolution.worker.start(job)
+ return job
diff --git a/harnessgrad/personal/planning.py b/harnessgrad/personal/planning.py
index fa7c61fd..b54b4ef3 100644
--- a/harnessgrad/personal/planning.py
+++ b/harnessgrad/personal/planning.py
@@ -5,6 +5,7 @@
from harnessgrad.improvement.contracts import selected_surfaces
from harnessgrad.personal.contracts import encode
+from harnessgrad.personal.reproduction import INSTRUCTION_REPRODUCTION
SYSTEM = (
'Plan a personal Harness change using only the supplied user feedback, selected evidence, '
@@ -20,6 +21,11 @@
'For a behavior fix with missing/incomplete evidence, ask for context first. '
'Checks and plans grant no execution or write permission.'
)
+INSTRUCTION_REVIEW_GUIDANCE = (
+ ' If the requested comparison checks whether instruction.md contains the exact rule below, '
+ 'use this registered reproduction object verbatim: ' + encode(INSTRUCTION_REPRODUCTION) + '. '
+ 'For other objectives or observed behavior, describe the appropriate comparison in your own words.'
+)
def _text(value, label):
diff --git a/harnessgrad/personal/proposal_jobs.py b/harnessgrad/personal/proposal_jobs.py
index 6414e9db..aa274d6a 100644
--- a/harnessgrad/personal/proposal_jobs.py
+++ b/harnessgrad/personal/proposal_jobs.py
@@ -9,6 +9,7 @@
from harnessgrad.personal.adapters.contracts import HostBinding, SurfaceError, TargetSelection
from harnessgrad.personal.contracts import SurfaceRef
+from harnessgrad.personal.evolution_contracts import PortRejected
from harnessgrad.personal.model import ModelSession
from harnessgrad.personal.profile import ModelLimits, ModelSettings
from harnessgrad.personal.proposal_run_store import ProposalStopped, ProposalUnavailable
@@ -21,9 +22,11 @@
class ProposalWorker:
"""One owned task at a time; an interrupted task never dispatches again automatically."""
- def __init__(self, store, adapter, settings: ModelSettings, *, fixture_client=None):
+ def __init__(self, store, adapter, settings: ModelSettings, *, fixture_client=None,
+ evolution_submit=None):
self.store, self.adapter, self.settings = store, adapter, settings
self.fixture_client = fixture_client
+ self.evolution_submit = evolution_submit
self.owner = uuid.uuid4().hex
self._lock = Lock()
self._closing = Event()
@@ -135,18 +138,33 @@ def guard_reservation(db, active_job_id):
prepared = self.adapter.prepare_extension(snapshot, candidate['files'])
self.adapter.verify_selected(binding, snapshot)
check_open()
+ review = {'evolution_job': None}
+ if self.evolution_submit is not None:
+ try:
+ review['evolution_job'] = self.evolution_submit(
+ project_id, feedback_id, snapshot, prepared, candidate['files'],
+ intent=plan['intent'], conditions=tuple(plan['criteria']),
+ reproduction=plan['reproduction'],
+ )
+ except PortRejected as error:
+ if error.reason_code not in ('scenario_unavailable', 'invalid_conditions'):
+ raise
+ review['evolution_review'] = {'status': 'unmeasured', 'reason_code': error.reason_code}
self.store.models.complete(model.job_id)
advance('ready', result={
'paths': [change.surface.path for change in prepared.changes], 'diff': prepared.diff,
'snapshot_sha256': prepared.snapshot_sha256, 'prepared_sha256': prepared.prepared_sha256,
'plan_id': record['record_id'], 'candidate_id': candidate['record_id'],
'fixture': candidate['fixture'], 'applied': False, 'verified': False,
+ **review,
})
except ProposalStopped:
return
except (SurfaceError, ProposalUnavailable, ValueError, OSError, RuntimeError, sqlite3.Error) as error:
unavailable = isinstance(error, ProposalUnavailable)
code = error.code if isinstance(error, (SurfaceError, ProposalUnavailable)) else 'proposal_failed'
+ if isinstance(error, PortRejected):
+ code = error.reason_code
try:
advance('interrupted' if unavailable else 'failed', result={'code': code})
except ProposalStopped:
diff --git a/harnessgrad/personal/proposal_run_store.py b/harnessgrad/personal/proposal_run_store.py
index f3cd143f..9ef3b3d2 100644
--- a/harnessgrad/personal/proposal_run_store.py
+++ b/harnessgrad/personal/proposal_run_store.py
@@ -1,7 +1,8 @@
"""Project-scoped proposal receipts and replayable state transitions."""
from __future__ import annotations
-from harnessgrad.personal.contracts import decode, encode, identifier
+from harnessgrad.personal import records
+from harnessgrad.personal.contracts import decode, digest, encode, identifier
ACTIVE = ('collecting', 'planning', 'proposing', 'checking')
TERMINAL = ('ready', 'needs_input', 'no_change', 'failed', 'interrupted', 'cancelled')
@@ -51,8 +52,31 @@ def get(self, project_id: str, feedback_id: str, owner: str | None) -> dict | No
status = row['status']
if row['owner'] != owner and status in ACTIVE:
status = 'interrupted'
- return {'feedback_id': feedback_id, 'status': status, 'job_id': row['job_id'],
- 'result': decode(row['result']) if row['result'] is not None else None}
+ result = decode(row['result']) if row['result'] is not None else None
+ if status == 'ready' and result and row['job_id'] and result.get('plan_id') and result.get('candidate_id'):
+ self._add_frozen_text(project_id, feedback_id, row['job_id'], result)
+ return {'feedback_id': feedback_id, 'status': status, 'job_id': row['job_id'], 'result': result}
+
+ def _add_frozen_text(self, project_id, feedback_id, job, result):
+ # Both immutable B publications predate C. Never reopen the live project on a history read.
+ try:
+ job_dir = digest(job)
+ plan_dir = self.events.path.parent / 'plans' / job_dir
+ candidate = records.read(self.events.path.parent / 'candidates' / job_dir, result['candidate_id'])
+ if candidate['plan_id'] != result['plan_id']:
+ return
+ for folder in (plan_dir, plan_dir / 'clarification', plan_dir.parent):
+ try:
+ plan = records.read(folder, result['plan_id'])
+ except (OSError, ValueError):
+ continue
+ if all((item['job_id'], item['project_id'], item['feedback_id']) == (job, project_id, feedback_id)
+ for item in (candidate, plan)):
+ original = plan['selected_input']['surfaces']['instruction.md']
+ result.update(original_text=original, candidate_sha256=digest({'files': candidate['files']}))
+ break
+ except (KeyError, OSError, ValueError):
+ pass # Older or unavailable publications still have their saved Diff.
def after(self, project_id: str, feedback_id: str, after: int) -> list[dict]:
if type(after) is not int or not 0 <= after < 2**63:
diff --git a/harnessgrad/personal/reproduction.py b/harnessgrad/personal/reproduction.py
index 6524599a..1d9daf3c 100644
--- a/harnessgrad/personal/reproduction.py
+++ b/harnessgrad/personal/reproduction.py
@@ -14,6 +14,11 @@
from harnessgrad.personal.contracts import digest, encode, identifier
SCHEMA = 'harnessgrad.personal.evolution-check.v1'
+INSTRUCTION_SCENARIO = 'python-related-tests'
+INSTRUCTION_RULE = 'Run related tests before delivery after changing Python code.'
+INSTRUCTION_REPRODUCTION = {
+ 'scenario': INSTRUCTION_SCENARIO, 'input': 'Review instruction text', 'expected': INSTRUCTION_RULE,
+}
MAX_LOG_BYTES = 64 * 1024
MAX_FILES = 50
MAX_FILE_BYTES = 64 * 1024
@@ -84,6 +89,31 @@ class ComparisonReport:
apply_eligible: bool
+class ScenarioMismatch(ValueError):
+ """Frozen artifacts cannot be compared by the selected registered scenario."""
+
+
+def instruction_scenario(baseline: dict[str, str], candidate: dict[str, str]) -> ReproductionScenario:
+ if any(set(files) != {'instruction.md'} or not isinstance(files['instruction.md'], str)
+ for files in (baseline, candidate)):
+ raise ScenarioMismatch('scenario_mismatch')
+ test = (
+ 'import pathlib\nimport unittest\n\n'
+ f'RULE = {INSTRUCTION_RULE!r}\n\n'
+ 'class InstructionPolicyTest(unittest.TestCase):\n'
+ ' def test_related_tests_rule(self):\n'
+ " text = pathlib.Path('instruction.md').read_text(encoding='utf-8')\n"
+ ' self.assertIn(RULE, text)\n\n'
+ "if __name__ == '__main__':\n unittest.main()\n"
+ )
+ baseline_files = {**baseline, 'test_instruction_policy.py': test}
+ candidate_files = {**candidate, 'test_instruction_policy.py': test}
+ return ReproductionScenario(
+ INSTRUCTION_SCENARIO, baseline_files, candidate_files,
+ ('{python}', '-m', 'unittest', '-v', 'test_instruction_policy.py'), 5.0,
+ )
+
+
def _render_command(command: tuple[str, ...]) -> tuple[str, ...]:
return tuple(sys.executable if part == '{python}' else part for part in command)
@@ -152,6 +182,14 @@ def run_scenario(scenario: ReproductionScenario, state_root: Path, *, phase: str
def compare_scenario(scenario: ReproductionScenario, state_root: Path) -> ComparisonReport:
baseline = run_scenario(scenario, state_root, phase='baseline')
candidate = run_scenario(scenario, state_root, phase='candidate')
+ return compare_runs(scenario.scenario_id, baseline, candidate, state_root)
+
+
+def compare_runs(
+ scenario_id: str, baseline: RunRecord, candidate: RunRecord, state_root: Path,
+) -> ComparisonReport:
+ if baseline.scenario_id != scenario_id or candidate.scenario_id != scenario_id:
+ raise ScenarioMismatch('scenario_mismatch')
comparable = (baseline.command == candidate.command and baseline.reason_code is None
and candidate.reason_code is None and baseline.source_unchanged and candidate.source_unchanged)
if not comparable:
@@ -163,7 +201,7 @@ def compare_scenario(scenario: ReproductionScenario, state_root: Path) -> Compar
status, reason = 'retest_passed', None
else:
status, reason = 'retest_failed', 'candidate_failed'
- report = ComparisonReport('comparison_' + uuid.uuid4().hex, scenario.scenario_id, baseline, candidate,
+ report = ComparisonReport('comparison_' + uuid.uuid4().hex, scenario_id, baseline, candidate,
comparable, status, reason, status == 'retest_passed')
report_root = state_root / 'evolution-reports'
report_root.mkdir(parents=True, exist_ok=True)
diff --git a/harnessgrad/personal/service.py b/harnessgrad/personal/service.py
index 1613d247..d2245c68 100644
--- a/harnessgrad/personal/service.py
+++ b/harnessgrad/personal/service.py
@@ -1,14 +1,29 @@
"""Owned local use cases for feedback and read-only proposals."""
from __future__ import annotations
+from collections.abc import Callable
from pathlib import Path
+from dataclasses import asdict
import os
import stat
+import sys
from harnessgrad.personal.adapters.codex import CodexAdapter
+from harnessgrad.personal.adapters.contracts import HostBinding
from harnessgrad.personal.contracts import decode, source_events
from harnessgrad.personal.event_store import EventStore
+from harnessgrad.personal.evolution_contracts import Scope, SnapshotRef
+from harnessgrad.personal.evolution_service import PersonalEvolution
from harnessgrad.personal.inputs import PersonalFeedback
+from harnessgrad.personal.learning.contracts import LearningPolicyUpdate, LearningSource
+from harnessgrad.personal.learning.maintenance import MaintenanceService
+from harnessgrad.personal.learning.maintenance_contracts import VersionPort
+from harnessgrad.personal.learning.reflection import ReflectionService
+from harnessgrad.personal.learning.reflection_contracts import ExistingExperience
+from harnessgrad.personal.learning.service import LearningService
+from harnessgrad.personal.learning.store import LearningStore
+from harnessgrad.personal.learning.submissions import LearningSubmissions, ReviewReader, SCENARIO_ID
+from harnessgrad.personal.learning_artifacts import ProjectLearningArtifacts, LearningEvolutionQueue
from harnessgrad.personal.profile import ModelSettings
from harnessgrad.personal.proposal_jobs import INSTRUCTION, ProposalWorker
from harnessgrad.personal.proposal_run_store import ProposalUnavailable
@@ -19,19 +34,24 @@
def plain_directory(path: Path) -> Path:
absolute = path.expanduser().absolute()
for candidate in (absolute, *absolute.parents):
- if candidate.exists() and (candidate.is_symlink() or candidate.is_junction()):
+ if candidate.is_symlink() or candidate.is_junction():
raise ValueError('selected directory must not traverse links or junctions')
return absolute.resolve()
-def state_directory(path: Path) -> Path:
+def state_directory(path: Path, *, databases: tuple[str, ...] = ('personal.sqlite3', 'evolution.sqlite3')) -> Path:
root = plain_directory(path)
if root.is_relative_to(REPOSITORY):
raise ValueError('personal state must be outside the checkout')
root.mkdir(parents=True, exist_ok=True)
- for name in ('personal.sqlite3', 'personal.sqlite3-wal', 'personal.sqlite3-shm', 'connection.json'):
+ sidecars = ('', '-wal', '-shm', '-journal')
+ for name in ('connection.json', *(db + suffix for db in databases for suffix in sidecars)):
target = root / name
- if target.exists() and (target.is_symlink() or target.stat().st_nlink != 1 or not target.is_file()):
+ try:
+ metadata = target.lstat()
+ except FileNotFoundError:
+ continue
+ if not stat.S_ISREG(metadata.st_mode) or metadata.st_nlink != 1:
raise ValueError('personal state files must be ordinary single-link files')
return root
@@ -60,12 +80,17 @@ def __init__(self, state_root: Path, *, codex: Path | None = None, managed_hooks
self.codex = codex
self.managed_hooks = managed_hooks
self.adapter = CodexAdapter()
+ self.evolution = PersonalEvolution(self.root, self.store.feedback, self.adapter)
self.capabilities = self.adapter.probe(None, managed_hooks=managed_hooks).as_dict()
if proposal_settings is None and proposal_client is not None:
raise ValueError('proposal fixtures need explicit model settings')
- self.proposals = (ProposalWorker(self.store, self.adapter, proposal_settings, fixture_client=proposal_client)
+ self.proposals = (ProposalWorker(self.store, self.adapter, proposal_settings, fixture_client=proposal_client,
+ evolution_submit=self._submit_proposal_evolution)
if proposal_settings is not None else None)
+ def _submit_proposal_evolution(self, *args, **kwargs) -> dict:
+ return asdict(self.evolution.submit_proposal(*args, **kwargs))
+
def probe(self) -> dict:
self.capabilities = self.adapter.probe(self.codex, managed_hooks=self.managed_hooks).as_dict()
return self.capabilities
@@ -81,6 +106,30 @@ def add_project(self, path: Path) -> dict:
def import_session(self, project_id: str, value: dict) -> dict:
return self.store.import_events(project_id, source_events(value))
+ def open_learning(
+ self, project_id: str, source: LearningSource, *, ask: Callable[[str], dict],
+ read_existing: Callable[[Scope, SnapshotRef], tuple[ExistingExperience, ...]],
+ confirm_policy: Callable[[LearningPolicyUpdate], bool] | None = None,
+ reports: ReviewReader | None = None, versions: VersionPort | None = None,
+ ) -> LearningSubmissions:
+ """Wire the explicitly selected source and registered project to the local C queue."""
+ project_root = self.store.project_root(project_id)
+ scope = Scope('default', project_id)
+ root = state_directory(self.root, databases=('learning.sqlite3', 'evolution.sqlite3'))
+ binding = HostBinding(scope.profile_id, project_id, 'project', project_root, None, sys.platform, 'bypass')
+ artifacts = ProjectLearningArtifacts(root / 'evolution-artifacts', binding, self.adapter)
+ store = LearningStore(root / 'learning.sqlite3')
+ intake = LearningService(store, source, confirm_policy=confirm_policy)
+ queue = LearningEvolutionQueue(self.evolution, artifacts,
+ read_evidence=lambda owner, ref: store.read_reflection_evidence(owner, (ref,)),
+ scenario_available=lambda owner, scenario: owner == scope and scenario == SCENARIO_ID)
+ reflection = ReflectionService(store, artifacts, queue, ask=ask, read_existing=read_existing,
+ resume_candidate=queue.resume_candidate)
+ maintenance = MaintenanceService(store, artifacts, queue, versions, accepted_candidate=queue.accepted_candidate,
+ resume_candidate=queue.resume_candidate)
+ return LearningSubmissions(scope, intake, reflection, artifacts, queue, reports,
+ local_comparison=self.evolution.read_comparison, maintenance=maintenance)
+
def submit_feedback(self, value: dict) -> dict:
return self.store.feedback.submit(PersonalFeedback.from_dict(value))
@@ -100,6 +149,9 @@ def proposal(self, project_id: str, feedback_id: str) -> dict | None:
def request_proposal(self, project_id: str, feedback_id: str) -> dict:
prior = self.proposal(project_id, feedback_id)
if prior is not None:
+ result = prior['result']
+ if prior['status'] == 'ready' and result and result.get('evolution_job'):
+ self.evolution.resume_proposal(project_id, feedback_id, result)
return prior
status = self.proposal_capability()['status']
if status != 'ready':
@@ -117,14 +169,18 @@ def cancel_proposal(self, project_id, feedback_id):
return self.store.proposal_runs.cancel(project_id, feedback_id, owner)
def close(self) -> None:
+ self.evolution.close()
if self.proposals is not None:
self.proposals.close()
def snapshot(self) -> dict:
usage = self.store.models.totals()
feedback_count = self.store.feedback.count()
- return {'schema': 'harnessgrad.personal.stage-a.v1', 'stage': 'B2' if feedback_count else ('B1' if usage['jobs'] else 'A'),
+ evolution_jobs = self.evolution.store.job_count()
+ stage = 'C2' if evolution_jobs else ('B2' if feedback_count else ('B1' if usage['jobs'] else 'A'))
+ return {'schema': 'harnessgrad.personal.stage-a.v1', 'stage': stage,
'read_only': True, 'model_calls': usage['logical_calls'], 'model_usage': usage,
'feedback_count': feedback_count, 'fts_available': self.store.evidence.fts,
'harness_changes': 0, 'projects': self.store.projects(),
- 'capabilities': self.capabilities, 'proposal_generation': self.proposal_capability()}
+ 'evolution_jobs': evolution_jobs, 'capabilities': self.capabilities,
+ 'proposal_generation': self.proposal_capability()}
diff --git a/harnessgrad/personal/workflow.py b/harnessgrad/personal/workflow.py
index 96b63349..07aa068a 100644
--- a/harnessgrad/personal/workflow.py
+++ b/harnessgrad/personal/workflow.py
@@ -48,13 +48,16 @@ def _validate_record(record, model, selected):
_reject_credential(record, model.settings.method.api_key)
-def _planner(clarified):
- return (planning.SYSTEM + ' The clarification is the user’s answer to your saved question.'
- if clarified else planning.SYSTEM)
+def _planners(selected, clarified):
+ original = (planning.SYSTEM + ' The clarification is the user’s answer to your saved question.'
+ if clarified else planning.SYSTEM)
+ if set(selected['surfaces']) == {'instruction.md'}:
+ return (original + planning.INSTRUCTION_REVIEW_GUIDANCE, original)
+ return (original,)
-def _binding(selected, clarified):
- return {'request_sha256': digest(selected), 'planner_sha256': digest(_planner(clarified))}
+def _binding(selected, planner):
+ return {'request_sha256': digest(selected), 'planner_sha256': digest(planner)}
def _plan_kind(kind, clarified):
@@ -83,20 +86,20 @@ def _reference(record_id, record, *, clarified=False):
def _freeze_request(model, selected, clarified):
store = model.store
- binding = _binding(selected, clarified)
kind, stage = _plan_kind('requested', clarified), _plan_stage(clarified)
with store.connection() as db, store.transaction(db):
prior = _event(db, model.job_id, kind)
- if prior is not None and prior != binding:
- raise ValueError('planning inputs differ from the frozen job')
# Older interrupted attempts have a model ledger but no request event.
- expected = digest({'stage': stage, 'system': _planner(clarified), 'prompt': encode(selected)})
- calls = db.execute('SELECT input_sha256 FROM model_calls WHERE job_id=? AND stage=?',
- (model.job_id, stage)).fetchall()
- if any(row['input_sha256'] != expected for row in calls):
- raise ValueError('planning inputs differ from the frozen job')
- if prior is None:
- store.add_event(db, model.job_id, kind, binding)
+ calls = {row['input_sha256'] for row in db.execute(
+ 'SELECT input_sha256 FROM model_calls WHERE job_id=? AND stage=?', (model.job_id, stage))}
+ for planner in _planners(selected, clarified):
+ binding = _binding(selected, planner)
+ expected = digest({'stage': stage, 'system': planner, 'prompt': encode(selected)})
+ if (prior is None or prior == binding) and (not calls or calls == {expected}):
+ if prior is None:
+ store.add_event(db, model.job_id, kind, binding)
+ return planner
+ raise ValueError('planning inputs differ from the frozen job')
def _finalize(model, selected, record_id, record, clarified):
@@ -104,7 +107,8 @@ def _finalize(model, selected, record_id, record, clarified):
question = record['plan']['question']
reference = {**_reference(record_id, record, clarified=clarified), 'storage': 'job'}
with store.connection() as db, store.transaction(db):
- if _event(db, model.job_id, _plan_kind('requested', clarified)) != _binding(selected, clarified):
+ frozen = _event(db, model.job_id, _plan_kind('requested', clarified))
+ if all(frozen != _binding(selected, planner) for planner in _planners(selected, clarified)):
raise ValueError('published plan has no matching frozen request')
kind = _plan_kind('recorded', clarified)
prior = _event(db, model.job_id, kind)
@@ -199,8 +203,8 @@ def plan_feedback(model, project_id: str, feedback_id: str, *, skills=None, inst
prior = _existing(model, selected, clarified)
if prior is not None:
return prior
- _freeze_request(model, selected, clarified)
- reply = model.for_stage(_plan_stage(clarified), system_prompt=_planner(clarified))(encode(selected))
+ planner = _freeze_request(model, selected, clarified)
+ reply = model.for_stage(_plan_stage(clarified), system_prompt=planner)(encode(selected))
_reject_credential(reply, model.settings.method.api_key)
plan = planning.parse_reply(reply, selected)
record = decode(encode({'schema': 'harnessgrad.personal.plan.v1', 'job_id': model.job_id,
diff --git a/pyproject.toml b/pyproject.toml
index c530286d..b4e38616 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -68,7 +68,7 @@ exclude = ["data.authored*", "data.candidates*", "console.uat*"]
]
"tools.testing" = ["test_costs.json"]
"console" = [
- "static/personal.html", "static/personal.js", "static/personal-window.js", "static/personal-draft.js", "static/personal-feedback.js", "static/personal-proposal.js", "static/personal.css",
+ "static/personal.html", "static/personal.js", "static/personal-window.js", "static/personal-draft.js", "static/personal-feedback.js", "static/personal-proposal.js", "static/personal-review.js", "static/personal.css",
"LICENSE-DSH", "DEVELOPMENT.md", "WORKBENCH.md", "static/app.css", "static/author.html", "static/author.js",
"static/console.js", "static/detail-i18n.js", "static/evidence.css",
"static/evidence.html", "static/evidence.js", "static/evolve.html", "static/xiaolv-preview.png", "static/harness.html",
diff --git a/tests/quality/test_personal_evolution_queue.py b/tests/quality/test_personal_evolution_queue.py
index 0e1426f6..5789637d 100644
--- a/tests/quality/test_personal_evolution_queue.py
+++ b/tests/quality/test_personal_evolution_queue.py
@@ -165,3 +165,21 @@ def test_queue_store_refuses_unknown_schema_objects_without_rewriting_them(tmp_p
with pytest.raises(ValueError, match='unrecognized'):
EvolutionQueueStore(path)
assert path.read_bytes() == before
+
+
+def test_v1_queue_migrates_transactionally_without_changing_existing_jobs(tmp_path):
+ value, _, queue = provider(tmp_path)
+ request = CandidateRequest.from_dict(value['request'])
+ job = queue.submit_candidate(request)
+ with sqlite3.connect(queue.store.path) as db:
+ db.execute('DROP TABLE evolution_questions')
+ db.execute('DROP TABLE evolution_reports')
+ db.execute('DROP TABLE evolution_artifacts')
+ db.execute('PRAGMA user_version=1')
+ migrated = EvolutionQueueStore(queue.store.path)
+ reopened = EvolutionQueue(migrated, queue.artifacts, read_evidence=queue.read_evidence,
+ scenario_available=queue.scenario_available)
+ assert reopened.read_job(job) == queue.read_job(job)
+ with sqlite3.connect(queue.store.path) as db:
+ assert db.execute('PRAGMA user_version').fetchone()[0] == 2
+ assert not db.execute('PRAGMA foreign_key_check').fetchall()
diff --git a/tests/quality/test_personal_evolution_recovery.py b/tests/quality/test_personal_evolution_recovery.py
new file mode 100644
index 00000000..02395e1b
--- /dev/null
+++ b/tests/quality/test_personal_evolution_recovery.py
@@ -0,0 +1,159 @@
+"""Single-owner offline execution and durable C replies across service restarts."""
+import multiprocessing
+import os
+from threading import Event
+import time
+from unittest.mock import patch
+
+import pytest
+
+import harnessgrad.personal.evolution_service as evolution
+from harnessgrad.personal.adapters import codex
+from harnessgrad.personal.evolution_contracts import PortRejected
+from harnessgrad.personal.service import PersonalService
+from test_personal_evolution_service import fixture, frozen_request
+
+pytestmark = pytest.mark.skipif(not codex._secure_access_available(), reason='safe selected read unavailable')
+
+
+def completed(service, job):
+ deadline = time.monotonic() + 8
+ while time.monotonic() < deadline:
+ view = service.evolution.read_job(job)
+ if view.status not in evolution.RUNNABLE_STATUSES:
+ assert view.status == 'retest_passed', view
+ return view
+ time.sleep(.01)
+ pytest.fail('evolution job did not finish')
+
+
+def statuses(service, job):
+ return [event.status for event in service.evolution.read_events(job, after=0).events]
+
+
+def test_two_services_submit_the_same_job_while_the_first_is_executing(tmp_path, monkeypatch):
+ first, project, _ = fixture(tmp_path)
+ second = PersonalService(first.root)
+ request = frozen_request(first, project)
+ runner = evolution.run_scenario
+ entered, release = Event(), Event()
+ calls = []
+
+ def run(scenario, root, *, phase):
+ calls.append(phase)
+ if phase == 'baseline':
+ entered.set()
+ assert release.wait(8)
+ return runner(scenario, root, phase=phase)
+
+ monkeypatch.setattr(evolution, 'run_scenario', run)
+ try:
+ job = first.evolution.submit_candidate(request)
+ assert entered.wait(8)
+ assert second.evolution.submit_candidate(request) == job
+ assert second.evolution.worker.start(job).status == 'reproducing'
+ finally:
+ release.set()
+ view = completed(second, job)
+ assert first.evolution.worker.start(job) == view
+ assert calls == ['baseline', 'candidate']
+ assert statuses(second, job) == ['created', 'collecting', 'reproducing', 'baseline_ready',
+ 'retesting', 'retest_passed']
+
+
+def exit_before_candidate(root, job, entered, quit_now):
+ """Process fixture stops after committing the baseline and admitting the retest."""
+ service = PersonalService(root)
+ runner = evolution.run_scenario
+
+ def run(scenario, root, *, phase):
+ if phase == 'candidate':
+ entered.set()
+ os._exit(17 if quit_now.wait(15) else 18)
+ return runner(scenario, root, phase=phase)
+
+ with patch.object(evolution, 'run_scenario', run):
+ service.evolution.worker.start(job)
+ Event().wait(18)
+
+
+def test_preempted_process_releases_ownership_and_retry_reuses_its_baseline(tmp_path):
+ service, project, _ = fixture(tmp_path)
+ request = frozen_request(service, project)
+ job = service.evolution.queue.submit_candidate(request)
+ ctx = multiprocessing.get_context('spawn')
+ entered, quit_now = ctx.Event(), ctx.Event()
+ process = ctx.Process(target=exit_before_candidate, args=(service.root, job, entered, quit_now))
+ process.start()
+ try:
+ assert entered.wait(10)
+ assert service.evolution.worker.start(job).status == 'retesting'
+ quit_now.set()
+ process.join(10)
+ assert process.exitcode == 17
+ finally:
+ if process.is_alive():
+ process.terminate()
+ process.join(5)
+ baseline_root, = (service.root / 'evolution-runs').iterdir()
+ assert service.evolution.submit_candidate(request) == job
+ view = completed(service, job)
+ report = service.evolution.read_comparison(job, view.comparison_ref)
+ assert report['baseline']['run_ref'] == baseline_root.name
+ assert len(list((service.root / 'evolution-runs').iterdir())) == 2
+ assert statuses(service, job) == ['created', 'collecting', 'reproducing', 'baseline_ready',
+ 'retesting', 'retest_passed']
+
+
+@pytest.mark.parametrize('crash_point', ['after_legacy_answer', 'after_requeue'])
+def test_reply_is_atomic_and_retry_dispatches_after_a_crash(tmp_path, monkeypatch, crash_point):
+ service, project, _ = fixture(tmp_path)
+ request = frozen_request(service, project, conditions=())
+ job = service.evolution.submit_candidate(request)
+ waiting = service.evolution.read_job(job)
+ assert waiting.status == 'needs_input'
+ question = waiting.question_id
+ answer = 'Check related tests before delivery.'
+ store = service.evolution.store
+ with monkeypatch.context() as scoped:
+ def fault(*args):
+ raise RuntimeError('simulated event failure')
+ scoped.setattr(store, '_record_transition', fault)
+ with pytest.raises(RuntimeError, match='simulated event failure'):
+ service.evolution.reply(job, question, answer)
+ assert service.evolution.read_question(job, question)['open']
+ assert service.evolution.read_job(job) == waiting
+
+ if crash_point == 'after_legacy_answer':
+ # The previous release could persist the answer separately from the collecting event.
+ with store.transaction() as db:
+ db.execute("UPDATE evolution_questions SET status='answered',response=? WHERE id=?", (answer, question))
+ else:
+ store.answer_question(job, question, answer)
+ assert service.evolution.read_job(job).status == 'collecting'
+ reopened = PersonalService(service.root)
+ with pytest.raises(PortRejected, match='idempotency_conflict'):
+ reopened.evolution.reply(job, question, 'Another answer.')
+ reopened.evolution.reply(job, question, answer)
+ done = completed(reopened, job)
+ assert reopened.evolution.reply(job, question, answer) == done
+ assert statuses(reopened, job) == ['created', 'collecting', 'needs_input', 'collecting',
+ 'reproducing', 'baseline_ready', 'retesting', 'retest_passed']
+
+
+def test_retry_publishes_comparison_saved_before_terminal_transition_by_older_worker(tmp_path):
+ service, project, _ = fixture(tmp_path)
+ request = frozen_request(service, project)
+ job = service.evolution.submit_candidate(request)
+ original = completed(service, job)
+ events = statuses(service, job)
+ report = service.evolution.read_comparison(job, original.comparison_ref)
+ with service.evolution.store.transaction() as db:
+ db.execute("DELETE FROM evolution_job_events WHERE job_id=? AND status=?", (job.job_id, original.status))
+ db.execute("UPDATE evolution_jobs SET status='retesting',comparison_ref=NULL WHERE id=?", (job.job_id,))
+ reopened = PersonalService(service.root)
+ assert reopened.evolution.submit_candidate(request) == job
+ assert completed(reopened, job) == original
+ assert reopened.evolution.read_comparison(job, original.comparison_ref) == report
+ assert statuses(reopened, job) == events
+ assert len(list((service.root / 'evolution-runs').iterdir())) == 2
diff --git a/tests/quality/test_personal_evolution_service.py b/tests/quality/test_personal_evolution_service.py
new file mode 100644
index 00000000..aea96534
--- /dev/null
+++ b/tests/quality/test_personal_evolution_service.py
@@ -0,0 +1,352 @@
+"""B feedback through the real C queue, worker, reports and HTTP receipts."""
+from __future__ import annotations
+
+from contextlib import contextmanager
+from dataclasses import asdict, replace
+import http.client
+import json
+from pathlib import Path
+import sys
+from threading import Thread
+import time
+
+import pytest
+
+from harnessgrad.personal import records
+from harnessgrad.personal.adapters import codex
+from harnessgrad.personal.adapters.contracts import HostBinding, TargetSelection
+from harnessgrad.personal.api import PersonalServer
+from harnessgrad.personal.contracts import SurfaceRef, digest, encode
+from harnessgrad.personal.evolution_contracts import CandidateRequest, PortRejected, Scope
+from harnessgrad.entrypoints.personal import main as personal_main
+from harnessgrad.personal.fixtures import ScriptedModelClient
+from harnessgrad.personal.profile import load_model_settings
+from harnessgrad.personal.reproduction import INSTRUCTION_RULE, ReproductionScenario
+from harnessgrad.personal.service import PersonalService
+
+SETTINGS = {
+ 'HG_METHOD_BASE_URL': 'http://127.0.0.1:1/v1', 'HG_METHOD_MODEL': 'offline-proposal',
+ 'HG_METHOD_API_KEY': 'never-used-by-scripted-client',
+}
+PLAN = {
+ 'decision': 'plan_ready', 'intent': 'preference',
+ 'objective': 'Require related tests before delivery', 'reason': 'Explicit user feedback',
+ 'targets': ['instruction.md'], 'criteria': ['changes Python code'], 'question': None,
+ 'reproduction': {'scenario': 'python-related-tests', 'input': 'Review instruction text',
+ 'expected': INSTRUCTION_RULE},
+}
+
+
+@contextmanager
+def running(service):
+ server = PersonalServer(service)
+ thread = Thread(target=server.serve_forever, kwargs={'poll_interval': .02}, daemon=True)
+ thread.start()
+
+ def request(path, value=None):
+ connection = http.client.HTTPConnection('127.0.0.1', server.server_port, timeout=5)
+ headers = {'Authorization': 'Bearer ' + server.token, 'Content-Type': 'application/json'}
+ try:
+ connection.request('GET' if value is None else 'POST', '/api/personal/' + path,
+ body=None if value is None else json.dumps(value), headers=headers)
+ response = connection.getresponse()
+ return response.status, json.loads(response.read())
+ finally:
+ connection.close()
+
+ try:
+ yield request
+ finally:
+ service.close()
+ server.shutdown(); server.server_close(); thread.join(timeout=5)
+
+
+def terminal(request, path, *, statuses=('retest_passed', 'retest_failed', 'not_reproduced',
+ 'not_comparable', 'failed', 'needs_input')):
+ deadline = time.monotonic() + 8
+ while time.monotonic() < deadline:
+ status, body = request(path)
+ assert status == 200, body
+ if body['status'] in statuses:
+ return body
+ time.sleep(.02)
+ pytest.fail('evolution job did not reach a review state')
+
+
+def finish_proposal(request, path, *, expected='ready'):
+ assert request(path, {})[0] == 200
+ deadline = time.monotonic() + 8
+ while time.monotonic() < deadline:
+ proposal = request(path)[1]['proposal']
+ if proposal['status'] in ('ready', 'failed'):
+ assert proposal['status'] == expected, proposal
+ return proposal
+ time.sleep(.02)
+ pytest.fail(f'proposal did not reach {expected}')
+
+
+def fixture(tmp_path, *, text='Keep changelogs concise.\n', client=None):
+ tmp_path.mkdir(parents=True, exist_ok=True)
+ project = tmp_path / 'project'; project.mkdir()
+ instruction = project / 'AGENTS.md'; instruction.write_bytes(text.encode('utf-8'))
+ service = PersonalService(
+ tmp_path / 'state', proposal_client=client,
+ proposal_settings=load_model_settings(SETTINGS) if client is not None else None,
+ )
+ project_id = service.add_project(project)['id']
+ return service, project_id, instruction
+
+
+def feedback(service, project_id, key='feedback-1'):
+ return service.submit_feedback({
+ 'project_id': project_id, 'kind': 'explicit_request',
+ 'text': '修改 Python 后,交付前运行相关测试', 'evidence': [],
+ 'idempotency_key': key, 'draft_revision': None,
+ })
+
+
+def frozen_request(service, project_id, *, conditions=('changes Python code',)):
+ item = feedback(service, project_id)
+ root = service.store.project_root(project_id)
+ binding = HostBinding('default', project_id, 'project', root, None, sys.platform, 'bypass')
+ target = TargetSelection('project-instructions', 'instruction', SurfaceRef('project', 'AGENTS.md'))
+ snapshot = service.adapter.collect_selected(binding, (target,))
+ scope = Scope('default', project_id)
+ frozen = service.evolution.artifacts.register_snapshot(scope, snapshot)
+ candidate = service.evolution.artifacts.register_candidate(
+ scope, frozen.ref, {'instruction.md': snapshot.files[0].text + INSTRUCTION_RULE + '\n'},
+ )
+ return CandidateRequest(
+ *scope.key(), ('project-instructions',), frozen.ref, frozen.sha256,
+ candidate.ref, candidate.sha256, (item['id'],), 'preference', conditions,
+ 'python-related-tests', 'candidate-' + item['id'],
+ )
+
+
+@pytest.mark.skipif(not codex._secure_access_available(), reason='safe selected read unavailable')
+def test_feedback_proposal_runs_real_c_job_and_report_survives_restart(tmp_path):
+ original = 'Keep changelogs concise.\n'
+ edited = original + INSTRUCTION_RULE + '\n'
+ client = ScriptedModelClient([PLAN, {'edits': [{'path': 'instruction.md', 'old': original,
+ 'new': edited}]}])
+ service, project_id, instruction = fixture(tmp_path, text=original, client=client)
+ other = tmp_path / 'other'; other.mkdir(); (other / 'AGENTS.md').write_text('Other.\n')
+ other_id = service.add_project(other)['id']
+ receipt = feedback(service, project_id)
+ proposal_path = f'projects/{project_id}/feedback/{receipt["id"]}/proposal'
+ with running(service) as request:
+ proposal = finish_proposal(request, proposal_path)
+ assert encode(PLAN['reproduction']) in client.requests[0]['messages'][0]['content']
+ job = proposal['result']['evolution_job']
+ path = f'projects/{project_id}/evolution/{job["job_id"]}'
+ view = terminal(request, path)
+ assert view['status'] == 'retest_passed' and view['comparison_ref']
+ status, page = request(path + '/events?after=0')
+ assert status == 200
+ assert [row['status'] for row in page['events']] == [
+ 'created', 'collecting', 'reproducing', 'baseline_ready', 'retesting', 'retest_passed',
+ ]
+ status, report = request(path + '/comparisons/' + view['comparison_ref'])
+ assert status == 200 and report['apply_eligible'] and report['comparable']
+ assert report['verification'] == {'status': 'instruction_text_verified',
+ 'label': '已验证指令文本',
+ 'later_behavior': 'unmeasured'}
+ assert report['job'] == job and report['candidate_sha256']
+ assert report['snapshot_sha256'] == proposal['result']['snapshot_sha256']
+ assert report['baseline']['exit_code'] != 0 and report['candidate']['exit_code'] == 0
+ assert report['baseline']['command'] == report['candidate']['command']
+ assert report['baseline']['run_ref'] != report['candidate']['run_ref']
+ assert request(f'projects/{other_id}/evolution/{job["job_id"]}')[0] == 404
+ saved = (job, view, report, proposal)
+ assert instruction.read_bytes() == original.encode()
+
+ reopened = PersonalService(service.root)
+ with running(reopened) as request:
+ job, view, report, proposal = saved
+ path = f'projects/{project_id}/evolution/{job["job_id"]}'
+ assert request(path)[1] == view
+ assert request(path + '/comparisons/' + view['comparison_ref'])[1] == report
+ assert request(proposal_path)[1]['proposal'] == proposal
+
+
+@pytest.mark.skipif(not codex._secure_access_available(), reason='safe selected read unavailable')
+def test_ready_proposal_retry_after_restart_resumes_only_its_acknowledged_review(tmp_path, monkeypatch):
+ original = 'Keep changelogs concise.\n'
+ edit = {'path': 'instruction.md', 'old': original, 'new': original + INSTRUCTION_RULE + '\n'}
+ client = ScriptedModelClient([PLAN, {'edits': [edit]}])
+ first, project_id, instruction = fixture(tmp_path, text=original, client=client)
+ receipt = feedback(first, project_id, 'original')
+ proposal_path = f'projects/{project_id}/feedback/{receipt["id"]}/proposal'
+ # Stop at the admission boundary: B can acknowledge its diff and C has no live worker.
+ monkeypatch.setattr(first.evolution.worker, 'start', first.evolution.read_job)
+ with running(first) as request:
+ proposal = finish_proposal(request, proposal_path)
+ job = proposal['result']['evolution_job']
+ review_path = f'projects/{project_id}/evolution/{job["job_id"]}'
+ assert request(review_path)[1]['status'] == 'collecting'
+ reopened = PersonalService(first.root)
+ with running(reopened) as request:
+ assert reopened.proposal_capability()['status'] == 'unconfigured'
+ assert request(proposal_path) == (200, {'proposal': proposal})
+ assert request(review_path)[1]['status'] == 'collecting'
+ assert not (first.root / 'evolution-runs').exists()
+ other = feedback(reopened, project_id, 'other')
+ with pytest.raises(PortRejected, match='out_of_scope'):
+ reopened.evolution.resume_proposal(project_id, other['id'], proposal['result'])
+ assert request(review_path)[1]['status'] == 'collecting'
+ assert request(proposal_path, {}) == (200, {'proposal': proposal})
+ done = terminal(request, review_path)
+ assert done['job'] == job and done['status'] == 'retest_passed'
+ assert request(proposal_path, {}) == (200, {'proposal': proposal})
+ assert request(review_path) == (200, done)
+ assert reopened.evolution.store.job_count() == 1
+ assert reopened.store.models.usage(proposal['job_id'])['logical_calls'] == len(client.requests) == 2
+ assert len(list((first.root / 'evolution-runs').iterdir())) == 2
+ assert instruction.read_bytes() == original.encode()
+
+
+@pytest.mark.skipif(not codex._secure_access_available(), reason='safe selected read unavailable')
+@pytest.mark.parametrize(('reproduction_changes', 'criterion', 'reason'), [
+ ({'scenario': 'Review release notes'}, 'Keep release notes concise', 'scenario_unavailable'),
+ ({'input': 'Run the agent on a Python change'}, 'Observe the agent', 'scenario_unavailable'),
+ ({'expected': 'Publish the test report'}, 'Inspect the report', 'scenario_unavailable'),
+ ({}, '条' * 342, 'invalid_conditions'),
+])
+def test_ineligible_review_preserves_ready_proposal(tmp_path, reproduction_changes, criterion, reason):
+ original = 'Keep changelogs concise.\n'
+ edited = original + INSTRUCTION_RULE + '\n'
+ plan = {**PLAN, 'criteria': [criterion], 'reproduction': {**PLAN['reproduction'], **reproduction_changes}}
+ client = ScriptedModelClient([plan, {'edits': [{'path': 'instruction.md', 'old': original, 'new': edited}]}])
+ service, project_id, instruction = fixture(tmp_path, text=original, client=client)
+ item = feedback(service, project_id)
+ path = f'projects/{project_id}/feedback/{item["id"]}/proposal'
+ with running(service) as request:
+ proposal = finish_proposal(request, path)
+ result = proposal['result']
+ assert INSTRUCTION_RULE in result['diff'] and not result['verified']
+ assert result['evolution_job'] is None
+ assert result['evolution_review'] == {'status': 'unmeasured', 'reason_code': reason}
+ saved = records.read(service.root / 'plans' / digest(proposal['job_id']), result['plan_id'])
+ assert saved['plan']['reproduction'] == plan['reproduction']
+ assert saved['plan']['criteria'] == [criterion]
+ assert service.evolution.store.job_count() == 0
+ assert not (service.root / 'evolution-runs').exists()
+ with running(PersonalService(service.root)) as request:
+ assert request(path)[1]['proposal'] == proposal
+ assert instruction.read_bytes() == original.encode()
+
+
+@pytest.mark.skipif(not codex._secure_access_available(), reason='safe selected read unavailable')
+def test_rejected_snapshot_fails_the_proposal_with_its_original_reason(tmp_path, monkeypatch):
+ original = 'Keep changelogs concise.\n'
+ edit = {'path': 'instruction.md', 'old': original, 'new': original + INSTRUCTION_RULE + '\n'}
+ client = ScriptedModelClient([PLAN, {'edits': [edit]}])
+ service, project_id, _ = fixture(tmp_path, text=original, client=client)
+ item = feedback(service, project_id)
+ path = f'projects/{project_id}/feedback/{item["id"]}/proposal'
+
+ def stale(_scope, _snapshot):
+ raise PortRejected('stale_snapshot')
+
+ monkeypatch.setattr(service.evolution.artifacts, 'register_snapshot', stale)
+ with running(service) as request:
+ proposal = finish_proposal(request, path, expected='failed')
+ assert proposal['result'] == {'code': 'stale_snapshot'}
+ assert service.evolution.store.job_count() == 0
+
+
+@pytest.mark.skipif(not codex._secure_access_available(), reason='safe selected read unavailable')
+def test_missing_condition_questions_then_resumes_the_same_job(tmp_path):
+ service, project_id, instruction = fixture(tmp_path)
+ request_value = frozen_request(service, project_id, conditions=())
+ with running(service) as request:
+ body = request('projects/' + project_id + '/evolution', {
+ key: value for key, value in request_value.as_dict().items()
+ if key not in ('profile_id', 'project_id')
+ })[1]
+ job_id = body['job_id']
+ path = f'projects/{project_id}/evolution/{job_id}'
+ waiting = terminal(request, path)
+ assert waiting['status'] == 'needs_input' and waiting['reason_code'] == 'missing_evidence'
+ answer = {'question_id': waiting['question_id'],
+ 'answer': 'Verify the related-tests rule for Python changes.'}
+ question_path = path + '/questions/' + waiting['question_id']
+ code, question = request(question_path)
+ assert code == 200 and question['open'] and question['prompt'] and question['job'] == waiting['job']
+ assert request(path + '/reply', answer)[0] == 200
+ done = terminal(request, path, statuses=('retest_passed', 'failed', 'not_comparable'))
+ assert done['job']['job_id'] == job_id and done['status'] == 'retest_passed'
+ assert request(path + '/reply', answer) == (200, done)
+ assert request(question_path)[1]['open'] is False
+ assert request(path + '/reply', {**answer, 'answer': 'Different answer'})[0] == 409
+ statuses = [row['status'] for row in request(path + '/events?after=0')[1]['events']]
+ assert statuses[:4] == ['created', 'collecting', 'needs_input', 'collecting']
+ invalid = request(path + '/events?after=bad')
+ assert invalid[0] == 400 and invalid[1]['code'] == 'invalid_cursor'
+ assert instruction.read_text() == 'Keep changelogs concise.\n'
+
+
+@pytest.mark.skipif(not codex._secure_access_available(), reason='safe selected read unavailable')
+def test_timeout_and_stale_snapshot_leave_specific_failure_receipts(tmp_path, monkeypatch):
+ service, project_id, instruction = fixture(tmp_path)
+ request_value = frozen_request(service, project_id)
+
+ import harnessgrad.personal.evolution_service as module
+ original_factory = module.instruction_scenario
+
+ def timeout_factory(baseline, candidate):
+ scenario = original_factory(baseline, candidate)
+ return replace(scenario, command=('{python}', '-c', 'import time; time.sleep(1)'),
+ timeout_seconds=.05)
+
+ monkeypatch.setattr(module, 'instruction_scenario', timeout_factory)
+ with running(service) as request:
+ job = service.evolution.submit_candidate(request_value)
+ path = f'projects/{project_id}/evolution/{job.job_id}'
+ done = terminal(request, path, statuses=('not_comparable', 'failed'))
+ assert done['status'] == 'not_comparable' and done['reason_code'] == 'execution_timeout'
+ report = request(path + '/comparisons/' + done['comparison_ref'])[1]
+ assert report['reason_code'] == 'execution_timeout' and not report['apply_eligible']
+
+ monkeypatch.setattr(module, 'instruction_scenario', original_factory)
+ mismatch_service, mismatch_project, _ = fixture(tmp_path / 'mismatch')
+ mismatch_request = frozen_request(mismatch_service, mismatch_project)
+ scope = mismatch_request.scope
+ wrong = mismatch_service.evolution.artifacts.register_candidate(
+ scope, mismatch_request.snapshot_ref, {'other.md': INSTRUCTION_RULE},
+ )
+ mismatch_request = replace(
+ mismatch_request, candidate_ref=wrong.ref, candidate_sha256=wrong.sha256,
+ idempotency_key='scenario-mismatch',
+ )
+ with running(mismatch_service) as request:
+ job = mismatch_service.evolution.submit_candidate(mismatch_request)
+ path = f'projects/{mismatch_project}/evolution/{job.job_id}'
+ done = terminal(request, path, statuses=('not_comparable', 'failed'))
+ assert done['status'] == 'not_comparable' and done['reason_code'] == 'scenario_mismatch'
+ assert done['comparison_ref'] is None
+
+ stale_service, stale_project, stale_file = fixture(tmp_path / 'stale')
+ stale_request = frozen_request(stale_service, stale_project)
+ stale_file.write_text('Externally edited.\n')
+ with running(stale_service) as request:
+ job = stale_service.evolution.queue.submit_candidate(stale_request)
+ stale_service.evolution.worker.start(job)
+ path = f'projects/{stale_project}/evolution/{job.job_id}'
+ done = terminal(request, path, statuses=('failed',))
+ assert done['reason_code'] == 'stale_snapshot' and done['comparison_ref'] is None
+
+
+@pytest.mark.skipif(not codex._secure_access_available(), reason='safe selected read unavailable')
+def test_empty_state_root_cli_demo_replays_the_original_job_without_writing_project(tmp_path, capsys):
+ project = tmp_path / 'project'; project.mkdir()
+ instruction = project / 'AGENTS.md'; instruction.write_text('Keep changelogs concise.\n')
+ state = tmp_path / 'state'
+ argv = ['evolution-demo', '--state-root', str(state), '--project', str(project)]
+ assert personal_main(argv) == 0
+ first = json.loads(capsys.readouterr().out)
+ assert first['view']['status'] == 'retest_passed' and first['report']['apply_eligible']
+ assert not first['applied'] and instruction.read_text() == 'Keep changelogs concise.\n'
+ assert personal_main(argv) == 0
+ second = json.loads(capsys.readouterr().out)
+ assert second['job'] == first['job'] and second['report'] == first['report']
diff --git a/tests/quality/test_personal_foundation.py b/tests/quality/test_personal_foundation.py
index c38acf11..f7b08905 100644
--- a/tests/quality/test_personal_foundation.py
+++ b/tests/quality/test_personal_foundation.py
@@ -18,7 +18,7 @@
from harnessgrad.personal.contracts import SourceEvent, decode, source_events
from harnessgrad.personal.event_store import EventStore
from harnessgrad.personal.fixtures import example
-from harnessgrad.personal.service import PersonalService
+from harnessgrad.personal.service import PersonalService, state_directory
ROOT = Path(__file__).resolve().parents[2]
@@ -149,6 +149,18 @@ def test_state_must_be_outside_checkout_and_selected_project(selected):
assert (project/'keep.txt').read_text() == 'original user data'
+@pytest.mark.parametrize('name', ['learning.sqlite3', 'learning.sqlite3-journal'])
+def test_state_directory_requires_ordinary_learning_database_paths(tmp_path, name):
+ root = tmp_path / 'state'
+ root.mkdir()
+ try:
+ (root / name).symlink_to(tmp_path / 'absent')
+ except OSError as error:
+ pytest.skip(f'symlinks unavailable: {error}')
+ with pytest.raises(ValueError, match='ordinary single-link'):
+ state_directory(root, databases=('learning.sqlite3',))
+
+
@pytest.fixture
def server(selected):
service, project, _ = selected
@@ -238,7 +250,8 @@ def test_owned_service_lifecycle_survives_restart_and_refuses_other_identity(tmp
def test_public_static_assets_are_served_without_authentication(server):
host, _ = server
- for path in ('/', '/personal.css', '/personal.js', '/personal-window.js', '/personal-draft.js', '/tokens.css'):
+ for path in ('/', '/personal.css', '/personal.js', '/personal-window.js', '/personal-draft.js',
+ '/personal-feedback.js', '/personal-review.js', '/personal-proposal.js', '/tokens.css'):
status, text = request(host, path, authenticated=False)
assert status == 200 and text
diff --git a/tests/quality/test_personal_learning_queue.py b/tests/quality/test_personal_learning_queue.py
new file mode 100644
index 00000000..24d64d52
--- /dev/null
+++ b/tests/quality/test_personal_learning_queue.py
@@ -0,0 +1,437 @@
+"""D intake and reflection against disk-backed selected artifacts and the real C queue."""
+from __future__ import annotations
+
+from dataclasses import replace
+from functools import partial
+import json
+import os
+from pathlib import Path
+import sqlite3
+import subprocess
+import sys
+from threading import Event
+import time
+
+import pytest
+
+from harnessgrad.personal.evolution_contracts import PortRejected, Scope
+from harnessgrad.personal.evolution_queue import EvolutionQueue
+from harnessgrad.personal.learning.contracts import LearningPolicyUpdate
+from harnessgrad.personal.learning.extension_contracts import ComparisonReport, RunRecord
+from harnessgrad.personal.learning.maintenance_contracts import ItemRevision, MaintenanceRequest, OperationRef, TaskContext
+from harnessgrad.personal.learning.source import SelectedImportSource
+from harnessgrad.personal.reproduction import INSTRUCTION_RULE
+from harnessgrad.personal.service import PersonalService
+from test_personal_reflection import SOURCE, source_item
+
+ORIGINAL = b'# Local instructions\r\n'
+RULE = '- ' + INSTRUCTION_RULE
+REPLY = {'decision': 'propose', 'kind': 'rule', 'path': 'instruction.md', 'topic_id': 'python-tests',
+ 'text': RULE, 'conditions': ['Python changed'], 'criterion': 'Check the instruction text.'}
+
+
+def open_submission(root, *, project='project-a', items=None, ask=None, reports=None):
+ service = PersonalService(root / 'state')
+ project_id = service.add_project(root / project)['id']
+ scope = Scope('default', project_id)
+ if items is None:
+ items = (source_item('one', 'private-context|Remember to run related tests'),)
+ source = SelectedImportSource(scope, SOURCE, items)
+ policy = LearningPolicyUpdate(scope, 0, True, (SOURCE,), 0, 10, 'opt-in', 'confirmed')
+ submissions = service.open_learning(project_id, source, ask=ask or (lambda _: REPLY),
+ read_existing=lambda *_: (), confirm_policy=lambda req: req == policy,
+ reports=reports)
+ return submissions, policy
+
+
+def final_view(app, job):
+ deadline = time.monotonic() + 8
+ while time.monotonic() < deadline:
+ view = app.read_job(job.job_id)
+ if view.status in ('retest_passed', 'retest_failed', 'failed', 'not_comparable', 'not_reproduced'):
+ return view
+ time.sleep(.02)
+ pytest.fail('C worker did not finish')
+
+
+def crash_after_accept(root, seq, *, wait_for_report=True):
+ def scripted(prompt):
+ assert 'private-context' not in prompt
+ print('scripted reflection', flush=True)
+ return REPLY
+
+ submissions, _ = open_submission(root, ask=scripted)
+ if not wait_for_report:
+ # The child exits at save_job while C still has an accepted, unfinished job.
+ submissions.queue.evolution.worker.verify_snapshot = lambda *_: Event().wait(15)
+
+ def exit_before_save(request, job):
+ ref = final_view(submissions, job).comparison_ref if wait_for_report else None
+ print(json.dumps({'job_id': job.job_id, 'key': submissions.reflection.reflections.key(request),
+ 'comparison_ref': ref}), flush=True)
+ os._exit(73)
+
+ submissions.reflection.reflections.save_job = exit_before_save
+ submissions.submit_decision(seq)
+ raise AssertionError('the queue did not accept the candidate')
+
+
+def setup_trigger(root, **options):
+ project = root / 'project-a'
+ project.mkdir()
+ (project / 'AGENTS.md').write_bytes(ORIGINAL)
+ submissions, policy = open_submission(root, **options)
+ submissions.intake.update_learning_policy(policy)
+ page = submissions.intake.poll_source(submissions.scope, SOURCE)
+ decision, = page.receipts
+ assert decision.decision.status == 'triggered'
+ return submissions, decision, page.cursor
+
+
+@pytest.mark.parametrize('completed', [False, True], ids=['worker-pending', 'report-published'])
+def test_lost_ack_replays_frozen_candidate_once_after_process_exit(tmp_path, completed):
+ _, decision, cursor = setup_trigger(tmp_path)
+ checkout = Path(__file__).resolve().parents[2]
+ script = ("import sys; from pathlib import Path; sys.path[:0] = sys.argv[1:3]; "
+ "from test_personal_learning_queue import crash_after_accept; "
+ "crash_after_accept(Path(sys.argv[3]), int(sys.argv[4]), wait_for_report=sys.argv[5]=='1')")
+ child = subprocess.run([sys.executable, '-B', '-X', 'utf8', '-c', script, str(checkout),
+ str(checkout / 'tests/quality'), str(tmp_path), str(decision.seq), str(int(completed))],
+ capture_output=True, text=True, timeout=30)
+ assert child.returncode == 73, child.stderr
+ call, before = child.stdout.splitlines()
+ assert call == 'scripted reflection'
+ before = json.loads(before)
+
+ restarted, _ = open_submission(tmp_path, ask=lambda _: pytest.fail('repeated reflection'))
+ page = restarted.intake.poll_source(restarted.scope, SOURCE)
+ assert (page.cursor, page.receipts) == (cursor, ())
+ saved, = restarted.intake.store.read_receipts(restarted.scope)
+ assert saved == decision
+
+ # The lost-ack replay must not collect a new copy of the live file.
+ path = tmp_path / 'project-a/AGENTS.md'
+ assert path.read_bytes() == ORIGINAL
+ changed = b'# Changed by the project owner\r\n'
+ if completed:
+ path.write_bytes(changed)
+ receipt = restarted.submit_decision(saved.seq)
+ assert receipt.job.job_id == before['job_id']
+ assert final_view(restarted, receipt.job).status == 'retest_passed'
+ candidate = receipt.decision.candidate
+ assert candidate.idempotency_key == before['key']
+ assert candidate.evidence_refs == decision.decision.evidence_refs
+ assert restarted.submit_decision(saved.seq) == receipt
+ baseline = restarted.artifacts.read_artifact(restarted.scope, candidate.snapshot_ref, kind='virtual_snapshot')
+ edited = restarted.artifacts.read_artifact(restarted.scope, candidate.candidate_ref, kind='text_candidate')
+ assert baseline.payload == {'files': {'instruction.md': ORIGINAL.decode()}}
+ assert edited.sha256 == candidate.candidate_sha256 and RULE in edited.payload['files']['instruction.md']
+ assert path.read_bytes() == (changed if completed else ORIGINAL)
+ assert restarted.read_job(receipt.job.job_id).job == receipt.job
+ first = restarted.read_events(receipt.job.job_id, after=0)
+ assert [event.status for event in first.events] == [
+ 'created', 'collecting', 'reproducing', 'baseline_ready', 'retesting', 'retest_passed']
+ assert restarted.read_events(receipt.job.job_id, after=first.next_after).events == ()
+ report = restarted.read_review(receipt.job.job_id)
+ if completed:
+ assert report['comparison_ref'] == before['comparison_ref']
+ else:
+ assert before['comparison_ref'] is None and report['comparison_ref']
+ assert (report['baseline']['exit_code'], report['candidate']['exit_code']) == (1, 0)
+ with sqlite3.connect(tmp_path / 'state/evolution.sqlite3') as db:
+ assert db.execute('SELECT count(*) FROM evolution_jobs').fetchone()[0] == 1
+ if not completed:
+ path.write_bytes(changed)
+ with pytest.raises(PortRejected, match='stale_snapshot'):
+ restarted.queue.submit_candidate(replace(candidate, idempotency_key='new-request'))
+
+
+@pytest.mark.parametrize('stage', ['reflection', 'correction'])
+@pytest.mark.parametrize('legacy', [False, True], ids=['published', 'v1-queue'])
+def test_replay_acknowledged_job_after_restart(tmp_path, monkeypatch, stage, legacy):
+ app, decision, _ = setup_trigger(tmp_path)
+ if stage == 'correction':
+ original = app.submit_decision(decision.seq)
+ assert final_view(app, original.job).status == 'retest_passed'
+ item = app.track_job(original.job.job_id)
+ correction = app.request_maintenance(MaintenanceRequest(
+ app.scope, 'correct', (ItemRevision(item.item_id, item.revision),),
+ 'Refine the condition', 'correction', 'Keep review notes brief.'))
+
+ def submit(service):
+ if stage == 'reflection':
+ return service.submit_decision(decision.seq)
+ return service.submit_maintenance_candidate(correction.decision_id)
+
+ with monkeypatch.context() as patch:
+ if legacy:
+ # The v1 queue accepted the request before C had an artifact registry or worker.
+ patch.setattr(app.queue, 'submit_candidate', partial(EvolutionQueue.submit_candidate, app.queue))
+ else:
+ # The service exited between durable acknowledgement and worker dispatch.
+ patch.setattr(app.queue.evolution.worker, 'start', lambda job: None)
+ saved = submit(app)
+ assert saved.job and app.read_job(saved.job.job_id).status == 'collecting'
+ count = app.queue.store.job_count()
+ reopened, _ = open_submission(tmp_path, ask=lambda _: pytest.fail('repeated reflection'))
+ assert submit(reopened) == saved
+ outcome = 'retest_passed' if stage == 'reflection' else 'retest_failed'
+ assert final_view(reopened, saved.job).status == outcome
+ report = reopened.read_review(saved.job.job_id)
+ request = reopened.queue.store.read_request(saved.job)
+ assert (report['candidate_id'], report['candidate_sha256'], report['snapshot_sha256']) == (
+ request.candidate_ref, request.candidate_sha256, request.snapshot_sha256)
+ assert reopened.queue.store.job_count() == count
+ assert (tmp_path / 'project-a/AGENTS.md').read_bytes() == ORIGINAL
+
+
+def test_cross_project_and_revoked_source_keep_original_decision(tmp_path):
+ app, decision, cursor = setup_trigger(tmp_path)
+ receipt = app.submit_decision(decision.seq)
+ assert final_view(app, receipt.job).status == 'retest_passed'
+ (tmp_path / 'project-b').mkdir()
+ other, _ = open_submission(tmp_path, project='project-b')
+ job = receipt.job.job_id
+ for read in (lambda: other.read_job(job), lambda: other.read_events(job, after=0),
+ lambda: other.read_review(job), lambda: other.submit_decision(decision.seq),
+ lambda: other.artifacts.read_artifact(other.scope, receipt.decision.candidate.candidate_ref,
+ kind='text_candidate')):
+ with pytest.raises(PortRejected, match='out_of_scope'):
+ read()
+ events = (source_item('one', 'private-context|Remember to run related tests'), source_item('two'))
+ reopened, _ = open_submission(tmp_path, items=events, ask=lambda _: pytest.fail('revoked source reflected'))
+ reopened.intake.update_learning_policy(LearningPolicyUpdate(app.scope, 1, True, (), 0, 10, 'revoke'))
+ page = reopened.intake.poll_source(app.scope, SOURCE)
+ assert page.reason_code == 'source_revoked' and page.cursor == cursor and not page.receipts
+ assert reopened.submit_decision(decision.seq).decision.reason_code == 'source_revoked'
+ assert reopened.intake.store.read_receipts(app.scope) == (decision,)
+ assert reopened.read_job(job).job == receipt.job
+
+
+def test_fresh_admission_binds_candidate_to_its_snapshot(tmp_path):
+ app, decision, _ = setup_trigger(tmp_path)
+ receipt = app.submit_decision(decision.seq)
+ assert final_view(app, receipt.job).status == 'retest_passed'
+ request = receipt.decision.candidate
+ original = tmp_path / 'project-a/AGENTS.md'
+ original.write_bytes(b'# Another baseline\n')
+ snapshot = app.artifacts.freeze_snapshot(app.scope, request.target_ids)
+ with pytest.raises(PortRejected, match='stale_snapshot'):
+ app.queue.submit_candidate(replace(request, snapshot_ref=snapshot.snapshot_ref,
+ snapshot_sha256=snapshot.snapshot_sha256, idempotency_key='mixed'))
+ with pytest.raises(PortRejected, match='invalid_candidate'):
+ app.artifacts.register_candidate(app.scope, snapshot.snapshot_ref, {'another.md': RULE})
+ assert original.read_bytes() == b'# Another baseline\n'
+
+
+def test_candidate_without_required_text_keeps_the_real_failure_report(tmp_path):
+ app, decision, _ = setup_trigger(tmp_path, ask=lambda _: {**REPLY, 'text': 'Keep notes brief.'})
+ receipt = app.submit_decision(decision.seq)
+ assert final_view(app, receipt.job).status == 'retest_failed'
+ report = app.read_review(receipt.job.job_id)
+ assert report['status'] == 'retest_failed'
+ assert report['verification'] == {'status': 'instruction_text_failed',
+ 'label': '候选指令文本未满足要求', 'later_behavior': 'unmeasured'}
+ assert report['baseline']['exit_code'] == report['candidate']['exit_code'] == 1
+ assert (tmp_path / 'project-a/AGENTS.md').read_bytes() == ORIGINAL
+
+
+def test_correct_a_saved_proposal_and_read_both_real_reviews_after_restart(tmp_path):
+ weak = '- Keep notes brief.'
+ app, decision, cursor = setup_trigger(tmp_path, ask=lambda _: {**REPLY, 'text': weak})
+ original = app.submit_decision(decision.seq)
+ assert final_view(app, original.job).status == 'retest_failed'
+ original_report = app.read_review(original.job.job_id)
+
+ # Start from the persisted D2 job as a caller upgrading an existing project would.
+ app, _ = open_submission(tmp_path, ask=lambda _: pytest.fail('unexpected reflection'))
+ item = app.track_job(original.job.job_id)
+ assert item.summary == weak and item.state == 'proposed'
+ request = MaintenanceRequest(app.scope, 'correct', (ItemRevision(item.item_id, item.revision),),
+ 'User clarified the delivery rule', 'fix-rule', RULE)
+ prepared = app.request_maintenance(request)
+ submitted = app.submit_maintenance_candidate(prepared.decision_id)
+ assert submitted.job != original.job and final_view(app, submitted.job).status == 'retest_passed'
+ reopened, _ = open_submission(tmp_path)
+ entry, = reopened.read_item_actions(item.item_id)
+ assert entry.request == request and entry.decision == submitted
+ assert reopened.request_maintenance(request) == submitted
+ assert reopened.submit_maintenance_candidate(prepared.decision_id) == submitted
+ revised = reopened.read_review(entry.decision.job.job_id)
+ frozen = submitted.candidate
+ assert revised['comparison_ref'] != original_report['comparison_ref']
+ assert revised['snapshot_sha256'] == original_report['snapshot_sha256'] == frozen.snapshot_sha256
+ assert revised['candidate_sha256'] == frozen.candidate_sha256 != original_report['candidate_sha256']
+ assert (revised['baseline']['exit_code'], revised['candidate']['exit_code']) == (1, 0)
+ assert revised['baseline']['command'] == revised['candidate']['command']
+ contents = reopened.artifacts.read_artifact(app.scope, frozen.candidate_ref, kind='text_candidate')
+ text = contents.payload['files']['instruction.md']
+ assert weak not in text and RULE in text and text.startswith(ORIGINAL.decode())
+ assert reopened.read_item_history(item.item_id) == (item,)
+ assert reopened.select_context(TaskContext(item.target_ids, item.conditions)) == ()
+ with pytest.raises(PortRejected, match='version_service_unavailable'):
+ reopened.reconcile_learning_item(item.item_id, OperationRef(submitted.job, 'missing-apply'))
+ assert reopened.read_item_history(item.item_id) == (item,)
+ assert reopened.read_review(item.job.job_id) == original_report
+ assert frozen.evidence_refs == item.evidence_refs == decision.decision.evidence_refs
+ assert reopened.intake.poll_source(app.scope, SOURCE).cursor == cursor
+ assert (tmp_path / 'project-a/AGENTS.md').read_bytes() == ORIGINAL
+ (tmp_path / 'project-b').mkdir()
+ other, _ = open_submission(tmp_path, project='project-b')
+ assert other.read_item_actions(item.item_id) == () and other.read_item_history(item.item_id) == ()
+ for operation in (lambda: other.track_job(item.job.job_id), lambda: other.request_maintenance(request),
+ lambda: other.submit_maintenance_candidate(prepared.decision_id),
+ lambda: other.read_review(submitted.job.job_id)):
+ with pytest.raises(PortRejected, match='out_of_scope'):
+ operation()
+
+
+@pytest.mark.parametrize('accepted', [False, True], ids=['before-acceptance', 'after-acceptance'])
+def test_retired_proposal_recovers_only_an_already_accepted_correction(tmp_path, monkeypatch, accepted):
+ app, decision, _ = setup_trigger(tmp_path)
+ original = app.submit_decision(decision.seq)
+ assert final_view(app, original.job).status == 'retest_passed'
+ item = app.track_job(original.job.job_id)
+ ref = ItemRevision(item.item_id, item.revision)
+ correct = app.request_maintenance(MaintenanceRequest(
+ app.scope, 'correct', (ref,), 'Narrow the rule', 'fix', 'Keep notes brief.'))
+ submit = app.queue.submit_candidate
+ jobs = []
+
+ def disconnect(candidate):
+ if accepted:
+ jobs.append(submit(candidate))
+ raise ConnectionError('disconnected')
+
+ with monkeypatch.context() as patch:
+ patch.setattr(app.queue, 'submit_candidate', disconnect)
+ with pytest.raises(ConnectionError):
+ app.submit_maintenance_candidate(correct.decision_id)
+ app.request_maintenance(MaintenanceRequest(app.scope, 'disable', (ref,), 'Retire this rule', 'stop'))
+ reopened, _ = open_submission(tmp_path)
+ if accepted:
+ retry = reopened.submit_maintenance_candidate(correct.decision_id)
+ assert retry.job == jobs[0] and final_view(reopened, retry.job).status == 'retest_failed'
+ report = reopened.read_review(retry.job.job_id)
+ assert report['verification']['status'] == 'instruction_text_failed'
+ assert report['baseline']['exit_code'] == report['candidate']['exit_code'] == 1
+ else:
+ with pytest.raises(PortRejected, match='revision_conflict'):
+ reopened.submit_maintenance_candidate(correct.decision_id)
+ with sqlite3.connect(tmp_path / 'state/evolution.sqlite3') as db:
+ assert db.execute('SELECT count(*) FROM evolution_jobs').fetchone()[0] == 1 + int(accepted)
+ old, disabled = reopened.read_item_history(item.item_id)
+ assert old == item and disabled.state == 'disabled' and disabled.evidence_refs == item.evidence_refs
+ archived = reopened.request_maintenance(MaintenanceRequest(
+ app.scope, 'archive', (ItemRevision(item.item_id, disabled.revision),), 'Withdraw proposal', 'withdraw'))
+ assert archived.status == 'recorded' and archived.restore_version_ref is None
+ with pytest.raises(PortRejected, match='invalid_maintenance_decision'):
+ reopened.request_rollback(archived.decision_id, 'no-file-was-installed')
+ assert reopened.track_job(original.job.job_id).state == 'archived'
+ assert (tmp_path / 'project-a/AGENTS.md').read_bytes() == ORIGINAL
+
+
+def test_proposal_correction_refuses_changed_baseline_and_revoked_source(tmp_path):
+ app, decision, _ = setup_trigger(tmp_path)
+ job = app.submit_decision(decision.seq).job
+ assert final_view(app, job).status == 'retest_passed'
+ item = app.track_job(job.job_id)
+ request = MaintenanceRequest(app.scope, 'correct', (ItemRevision(item.item_id, item.revision),),
+ 'Refine rule', 'prepare-correction', 'Keep notes brief.')
+ pending = app.request_maintenance(request)
+ instruction = tmp_path / 'project-a/AGENTS.md'
+ instruction.write_bytes(b'# User edited the file\n')
+ outcome = app.request_maintenance(replace(request, idempotency_key='after-edit'))
+ assert outcome.status == 'conflict' and outcome.reason_code == 'stale_snapshot'
+ with pytest.raises(PortRejected, match='stale_snapshot'):
+ app.submit_maintenance_candidate(pending.decision_id)
+ assert instruction.read_bytes() == b'# User edited the file\n'
+ instruction.write_bytes(ORIGINAL)
+ app.intake.update_learning_policy(LearningPolicyUpdate(app.scope, 1, True, (), 0, 10, 'revoke'))
+ with pytest.raises(PortRejected, match='out_of_scope'):
+ app.submit_maintenance_candidate(pending.decision_id)
+ assert app.queue.store.job_count() == 1
+
+
+@pytest.fixture
+def completed_v1_review(tmp_path):
+ class Reports:
+ def read_comparison(self, job, ref):
+ assert (job, ref) == (receipt.job, 'report')
+ return self.report
+
+ def read_run(self, job, ref):
+ assert job == receipt.job
+ return self.runs[ref]
+
+ # C's report ports are injected separately from the real queue provider.
+ reports = Reports()
+ app, decision, _ = setup_trigger(tmp_path, reports=reports)
+ receipt = app.submit_decision(decision.seq)
+ assert final_view(app, receipt.job).status == 'retest_passed'
+ candidate = receipt.decision.candidate
+ reports.report = ComparisonReport('report', receipt.job, candidate.candidate_ref, ('before',), ('after',),
+ True, 'retest_passed', None, True, candidate.candidate_sha256)
+ before = RunRecord('before', receipt.job, candidate.scenario_id, 'baseline', 1, 'f' * 64,
+ candidate.snapshot_sha256, None, None, ('text-check',), 1, None, False,
+ 'executed', 'not_met', None, True)
+ after = replace(before, run_ref='after', phase='candidate', prepared_sha256=candidate.candidate_sha256,
+ exit_code=0, judge_result='met')
+ reports.runs = {'before': before, 'after': after}
+ app.queue.transition(receipt.job, 'retest_passed', comparison_ref='report')
+ return app, receipt.job, reports
+
+
+def test_completed_job_resolves_only_its_scoped_report_and_runs(completed_v1_review):
+ app, job, reports = completed_v1_review
+ before, after = reports.runs['before'], reports.runs['after']
+ review = app.read_review(job.job_id)
+ assert (review.report, review.baseline, review.candidate) == (reports.report, (before,), (after,))
+ reports.runs['after'] = replace(after, snapshot_sha256='b' * 64)
+ with pytest.raises(PortRejected, match='invalid_run_receipt'):
+ app.read_review(job.job_id)
+ reports.runs['after'] = replace(after, prepared_sha256='a' * 64)
+ with pytest.raises(PortRejected, match='invalid_comparison_report'):
+ app.read_review(job.job_id)
+ reports.runs['after'] = replace(after, job=replace(job, project_id='other'))
+ with pytest.raises(PortRejected, match='out_of_scope'):
+ app.read_review(job.job_id)
+
+
+@pytest.mark.parametrize('ref,exit_code,judge', [
+ ('before', 0, 'met'), ('before', 0, 'not_met'), ('before', 1, 'unknown'),
+ ('before', None, 'not_met'), ('after', 1, 'met'), ('after', None, 'met'),
+])
+def test_v1_text_pass_rejects_contradictory_attempts(completed_v1_review, ref, exit_code, judge):
+ app, job, reports = completed_v1_review
+ run = reports.runs[ref]
+ field = run.phase + '_run_refs'
+ reports.report = replace(reports.report, **{field: (ref, 'retry')})
+ reports.runs['retry'] = replace(run, run_ref='retry', attempt=2, exit_code=exit_code, judge_result=judge)
+ with pytest.raises(PortRejected, match='invalid_comparison_report'):
+ app.read_review(job.job_id)
+
+
+def test_two_successful_v1_runs_support_only_the_baseline_passed_verdict(completed_v1_review):
+ app, job, reports = completed_v1_review
+ reports.runs['before'] = replace(reports.runs['before'], exit_code=0, judge_result='met')
+ with pytest.raises(PortRejected, match='invalid_comparison_report'):
+ app.read_review(job.job_id)
+ reports.report = replace(reports.report, verdict='not_reproduced', reason_code='baseline_passed')
+ app.queue.transition(job, 'not_reproduced', reason_code='baseline_passed', comparison_ref=reports.report.report_ref)
+ assert app.read_review(job.job_id).report == reports.report
+
+
+def test_v1_pass_rejects_a_different_candidate_command(completed_v1_review):
+ app, job, reports = completed_v1_review
+ reports.runs['after'] = replace(reports.runs['after'], command=('another-check',))
+ with pytest.raises(PortRejected, match='invalid_comparison_report'):
+ app.read_review(job.job_id)
+
+
+@pytest.mark.parametrize('status,reason', [('failed', None), ('retest_passed', 'execution_timeout')])
+def test_v1_pass_requires_a_matching_terminal_job(completed_v1_review, status, reason):
+ app, job, reports = completed_v1_review
+ app.queue.transition(job, status, reason_code=reason, comparison_ref=reports.report.report_ref)
+ with pytest.raises(PortRejected, match='invalid_comparison_report'):
+ app.read_review(job.job_id)
diff --git a/tests/quality/test_personal_maintenance.py b/tests/quality/test_personal_maintenance.py
index 1b583549..3cecb283 100644
--- a/tests/quality/test_personal_maintenance.py
+++ b/tests/quality/test_personal_maintenance.py
@@ -234,6 +234,35 @@ def test_archiving_a_disabled_but_still_installed_item_keeps_rollback_available(
assert service.reconcile_learning_item(SCOPE, active.item_id, operation).state == 'archived'
+def test_proposal_correction_activates_only_the_candidate_in_the_apply_receipt(lane):
+ store, c, reflection, (first, _) = lane
+ first = replace(first, constraints=('Preserve historical reports',))
+ original = reflection.submit(first)
+ service = MaintenanceService(store, c, c, c)
+ proposed = service.track_job(original.job)
+ assert proposed == service.track_reflection(first)
+ draft = service.request_maintenance(maintenance('correct', proposed, text=CORRECTED))
+ submitted = service.submit_candidate(SCOPE, draft.decision_id)
+ assert not service.select_context(SCOPE, TASK)
+ assert service.read_history(SCOPE, proposed.item_id) == (proposed,)
+
+ operation = c.apply(submitted.job)
+ ref = c.read_operation(operation).version_receipt_ref
+ key = (submitted.job, ref)
+ receipt = c.receipts[key]
+ c.receipts[key] = replace(receipt, candidate_id=original.decision.candidate.candidate_ref)
+ with pytest.raises(PortRejected, match='candidate_mismatch'):
+ service.reconcile_learning_item(SCOPE, proposed.item_id, operation)
+ assert service.read_history(SCOPE, proposed.item_id) == (proposed,)
+
+ c.receipts[key] = receipt
+ active = service.reconcile_learning_item(SCOPE, proposed.item_id, operation)
+ assert active.job == submitted.job and active.version_receipt_ref
+ assert active.summary == CORRECTED and active.state == 'active'
+ assert service.select_context(SCOPE, TASK) == (active,)
+ assert service.read_history(SCOPE, proposed.item_id) == (proposed, active)
+
+
def test_correction_replaces_only_after_verified_application(lane):
_, c, _, _ = lane
service, (active,) = start(lane)
diff --git a/tests/quality/test_personal_planning.py b/tests/quality/test_personal_planning.py
index 6439dbfa..6856fdc7 100644
--- a/tests/quality/test_personal_planning.py
+++ b/tests/quality/test_personal_planning.py
@@ -7,7 +7,7 @@
import pytest
-from harnessgrad.personal import records
+from harnessgrad.personal import planning, records
from harnessgrad.personal.contracts import decode, digest, encode
from harnessgrad.personal.event_store import EventStore
from harnessgrad.personal.fixtures import ScriptedModelClient
@@ -148,6 +148,24 @@ def test_failed_attempt_can_retry_the_same_input_with_the_same_budget(selected):
assert len(client.requests) == model.usage()['logical_calls'] == 2
+@pytest.mark.parametrize('keep_request_event', [True, False])
+def test_instruction_plan_retry_uses_the_original_frozen_prompt(selected, monkeypatch, keep_request_event):
+ service, project, feedback, _ = selected
+ surface = ('instruction.md', 'Run the selected task.')
+ model, client = session(selected, [reply(targets=['unknown.md']), reply(targets=['instruction.md'])])
+ with monkeypatch.context() as old:
+ old.setattr(planning, 'INSTRUCTION_REVIEW_GUIDANCE', '')
+ with pytest.raises(ValueError, match='undiscovered'):
+ plan_feedback(model, project, feedback, instruction=surface)
+ if not keep_request_event:
+ with service.store.connection() as db:
+ db.execute("DELETE FROM evolution_events WHERE job_id=? AND type='plan.requested'", (model.job_id,))
+ plan = plan_feedback(model, project, feedback, instruction=surface)
+ assert plan['plan']['decision'] == 'plan_ready'
+ assert len(client.requests) == 2
+ assert all(request['messages'][0]['content'] == planning.SYSTEM for request in client.requests)
+
+
@pytest.mark.parametrize('finished', [False, True])
def test_persisted_plan_remains_readable_after_execution_ends(selected, finished):
service, project, feedback, _ = selected
diff --git a/tests/quality/test_personal_proposal_flow.py b/tests/quality/test_personal_proposal_flow.py
index fce9a749..f958cbce 100644
--- a/tests/quality/test_personal_proposal_flow.py
+++ b/tests/quality/test_personal_proposal_flow.py
@@ -123,6 +123,8 @@ def complete(self, **kwargs):
assert run['status'] == 'ready', run
result = run['result']
assert result['paths'] == ['AGENTS.md']
+ assert result['original_text'].splitlines() == ['Run focused tests.']
+ assert len(result['candidate_sha256']) == 64
assert '+++ b/project/AGENTS.md' in result['diff']
assert '+Run focused tests and report the results.' in result['diff']
assert result['fixture'] and not result['applied'] and not result['verified']
@@ -133,6 +135,9 @@ def complete(self, **kwargs):
assert read_only(route)[1]['proposal'] == run
assert read_only(route, {})[1]['proposal'] == run
assert file.read_bytes() == original and len(client.requests) == 2
+ file.write_text('Changed after the proposal.', encoding='utf-8')
+ with running(PersonalService(service.root)) as restarted:
+ assert restarted(route)[1]['proposal'] == run
def test_opt_in_and_platform_unavailability_do_not_call_model(tmp_path, monkeypatch):
diff --git a/tests/quality/test_personal_reproduction.py b/tests/quality/test_personal_reproduction.py
index 0a4e2777..1867e909 100644
--- a/tests/quality/test_personal_reproduction.py
+++ b/tests/quality/test_personal_reproduction.py
@@ -8,7 +8,9 @@
import pytest
from harnessgrad.entrypoints.personal import main
-from harnessgrad.personal.reproduction import ReproductionScenario, compare_scenario, run_scenario
+from harnessgrad.personal.reproduction import (
+ ReproductionScenario, ScenarioMismatch, compare_scenario, instruction_scenario, run_scenario,
+)
FIXTURE = Path(__file__).parents[1] / 'fixtures' / 'personal_evolution_python.json'
@@ -17,6 +19,13 @@ def scenario() -> ReproductionScenario:
return ReproductionScenario.from_dict(json.loads(FIXTURE.read_text(encoding='utf-8')))
+def test_instruction_check_rejects_an_additional_virtual_surface():
+ baseline = {'instruction.md': 'Original rule', 'notes.md': 'Other selected surface'}
+ candidate = {**baseline, 'instruction.md': 'New rule'}
+ with pytest.raises(ScenarioMismatch):
+ instruction_scenario(baseline, candidate)
+
+
def test_c1_records_real_baseline_exit_logs_and_preserves_selected_sources(tmp_path):
record = run_scenario(scenario(), tmp_path, phase='baseline')
assert record.phase == 'baseline' and record.exit_code != 0 and not record.timed_out
diff --git a/tests/quality/test_wheel_console.py b/tests/quality/test_wheel_console.py
index 1e4f8031..ebf4293f 100644
--- a/tests/quality/test_wheel_console.py
+++ b/tests/quality/test_wheel_console.py
@@ -56,6 +56,28 @@ def run(argv):
python = str(runtime / "bin/python")
run([python, "-m", "pip", "install", "--no-index", "--no-deps", str(wheel)])
shutil.rmtree(source)
+ run([python, "-I", "-B", "-c", """
+import re, tempfile, threading, urllib.request
+from pathlib import Path
+from harnessgrad.personal.api import PersonalServer
+from harnessgrad.personal.service import PersonalService
+with tempfile.TemporaryDirectory() as scratch:
+ service = PersonalService(Path(scratch))
+ with PersonalServer(service) as server:
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ with urllib.request.urlopen(server.url, timeout=5) as response:
+ scripts = re.findall(r'