From 1cf6ba5ba0b10ada026803041196e29c55541f41 Mon Sep 17 00:00:00 2001 From: wwwaken Date: Mon, 30 Nov 2026 10:19:44 +0800 Subject: [PATCH 1/9] Connect personal proposals to evolution review (cherry picked from commit a5c35ca47e30f734effa3f062964621aa9476696) --- docs/personal-evolution-review.md | 53 ++++ harnessgrad/cli.py | 1 + harnessgrad/entrypoints/personal.py | 48 +++- harnessgrad/personal/api.py | 50 ++++ harnessgrad/personal/evolution_queue.py | 164 ++++++++++- harnessgrad/personal/evolution_service.py | 251 +++++++++++++++++ harnessgrad/personal/proposal_jobs.py | 11 +- harnessgrad/personal/reproduction.py | 38 ++- harnessgrad/personal/service.py | 21 +- .../quality/test_personal_evolution_queue.py | 18 ++ .../test_personal_evolution_service.py | 256 ++++++++++++++++++ 11 files changed, 890 insertions(+), 21 deletions(-) create mode 100644 docs/personal-evolution-review.md create mode 100644 harnessgrad/personal/evolution_service.py create mode 100644 tests/quality/test_personal_evolution_service.py diff --git a/docs/personal-evolution-review.md b/docs/personal-evolution-review.md new file mode 100644 index 00000000..d61a62ae --- /dev/null +++ b/docs/personal-evolution-review.md @@ -0,0 +1,53 @@ +# 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 B proposal result contains `evolution_job`, whose `(profile_id, project_id, job_id)` is the + stable C task identity. +- `GET /api/personal/projects/{project_id}/evolution/{job_id}` returns the current `JobView`. +- `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/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..5eaed10f 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 @@ -131,6 +133,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 +171,20 @@ 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 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 +196,19 @@ 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) == 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 +242,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_queue.py b/harnessgrad/personal/evolution_queue.py index 2a6eeed8..c232c87d 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,120 @@ 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: + if not isinstance(job, JobRef): + raise PortRejected('out_of_scope') + with closing(self.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 + + def save_report(self, job: JobRef, ref: str, value: dict) -> None: + identifier(ref) + self.scoped_job(job) + body = encode(value) + with self.transaction() as db: + prior = 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 prior and prior['body'] != body: + raise PortRejected('idempotency_conflict') + if prior is None: + db.execute('INSERT INTO evolution_reports VALUES (?,?,?,?,?)', + (*job.scope.key(), job.job_id, ref, body)) + + 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 open_question(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') + self.scoped_job(job) + with self.transaction() as db: + db.execute('INSERT OR IGNORE INTO evolution_questions VALUES (?,?,?,?,?,?,NULL)', + (*job.scope.key(), job.job_id, question_id, prompt, 'open')) + + def answer_question(self, job: JobRef, question_id: str, answer: str) -> bool: + identifier(question_id) + if not isinstance(answer, str) or not answer.strip() or len(answer.encode('utf-8')) > 16384: + raise PortRejected('invalid_request') + self.scoped_job(job) + with self.transaction() as db: + row = db.execute( + 'SELECT status,response 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') + if row['status'] == 'answered': + if row['response'] != answer: + raise PortRejected('idempotency_conflict') + return False + db.execute( + "UPDATE evolution_questions SET status='answered',response=? " + 'WHERE profile_id=? AND project_id=? AND job_id=? AND id=?', + (answer, *job.scope.key(), job.job_id, question_id), + ) + return True + + def answered(self, job: JobRef) -> bool: + self.scoped_job(job) + with closing(self.connection()) as db: + return bool(db.execute( + "SELECT 1 FROM evolution_questions WHERE profile_id=? AND project_id=? " + "AND job_id=? AND status='answered' LIMIT 1", (*job.scope.key(), job.job_id), + ).fetchone()) + + 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 @@ -198,13 +342,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)) diff --git a/harnessgrad/personal/evolution_service.py b/harnessgrad/personal/evolution_service.py new file mode 100644 index 00000000..6a7ce0d4 --- /dev/null +++ b/harnessgrad/personal/evolution_service.py @@ -0,0 +1,251 @@ +"""Personal-service assembly for frozen artifacts and offline evolution review.""" +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import asdict +from pathlib import Path +import sqlite3 +from threading import Event, Lock, 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, +) +from harnessgrad.personal.evolution_queue import EvolutionQueue, EvolutionQueueStore +from harnessgrad.personal.reproduction import ( + INSTRUCTION_SCENARIO, + ScenarioMismatch, + compare_runs, + instruction_scenario, + run_scenario, +) + + +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() + self._lock = Lock() + self._threads: dict[JobRef, Thread] = {} + + def close(self) -> None: + self._closing.set() + + def start(self, job: JobRef) -> JobView: + view = self.queue.read_job(job) + if view.status in ('needs_input', 'not_reproduced', 'no_change', 'retest_passed', 'retest_failed', + 'not_comparable', 'cancelled', 'interrupted', 'failed'): + return view + with self._lock: + active = self._threads.get(job) + if active is not None and active.is_alive(): + return view + thread = Thread(target=self._run, args=(job,), name='personal-evolution', daemon=True) + self._threads[job] = thread + thread.start() + return self.queue.read_job(job) + + def reply(self, job: JobRef, question_id: str, answer: str) -> JobView: + view = self.queue.read_job(job) + if view.status != 'needs_input' or view.question_id != question_id: + if not self.queue.store.answer_question(job, question_id, answer): + return view + raise PortRejected('out_of_scope') + changed = self.queue.store.answer_question(job, question_id, answer) + if changed: + self.queue.transition(job, 'collecting') + return self.start(job) + return self.queue.read_job(job) + + def _run(self, job: JobRef) -> None: + try: + request = self.queue.store.read_request(job) + if not request.conditions and not self.queue.store.answered(job): + question_id = 'question_' + digest(asdict(job))[:32] + self.queue.store.open_question( + job, question_id, + 'Which concrete condition should the fixed Python review scenario verify?', + ) + self.queue.transition(job, 'needs_input', reason_code='missing_evidence', + question_id=question_id) + 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']) + self.queue.transition(job, 'reproducing') + baseline = run_scenario(scenario, self.root, phase='baseline') + 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 + self.queue.transition(job, 'retesting') + revised = run_scenario(scenario, self.root, phase='candidate') + report = compare_runs(scenario.scenario_id, baseline, revised, self.root) + self.queue.store.save_report(job, report.comparison_ref, { + **asdict(report), 'job': asdict(job), 'snapshot_sha256': request.snapshot_sha256, + 'candidate_id': request.candidate_ref, 'candidate_sha256': request.candidate_sha256, + 'verification': {'status': 'instruction_text_verified', 'label': '已验证指令文本', + 'later_behavior': 'unmeasured'}, + }) + self.queue.transition(job, report.status, reason_code=report.reason_code, + comparison_ref=report.comparison_ref) + 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, ...], + ) -> JobRef: + 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, INSTRUCTION_SCENARIO, 'proposal_' + feedback_id, + ) + return self.submit_candidate(request) + + 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 reply(self, job: JobRef, question_id: str, answer: str) -> JobView: + return self.worker.reply(job, question_id, answer) diff --git a/harnessgrad/personal/proposal_jobs.py b/harnessgrad/personal/proposal_jobs.py index 6414e9db..9702a854 100644 --- a/harnessgrad/personal/proposal_jobs.py +++ b/harnessgrad/personal/proposal_jobs.py @@ -21,9 +21,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,12 +137,19 @@ def guard_reservation(db, active_job_id): prepared = self.adapter.prepare_extension(snapshot, candidate['files']) self.adapter.verify_selected(binding, snapshot) check_open() + evolution_job = None + if self.evolution_submit is not None: + evolution_job = self.evolution_submit( + project_id, feedback_id, snapshot, prepared, candidate['files'], + intent=plan['intent'], conditions=tuple(plan['criteria']), + ) 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, + 'evolution_job': evolution_job, }) except ProposalStopped: return diff --git a/harnessgrad/personal/reproduction.py b/harnessgrad/personal/reproduction.py index 6524599a..db2670df 100644 --- a/harnessgrad/personal/reproduction.py +++ b/harnessgrad/personal/reproduction.py @@ -14,6 +14,8 @@ 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.' MAX_LOG_BYTES = 64 * 1024 MAX_FILES = 50 MAX_FILE_BYTES = 64 * 1024 @@ -84,6 +86,32 @@ 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 (set(baseline) != set(candidate) or 'instruction.md' not in baseline + or any(not isinstance(path, str) or not isinstance(text, str) + for files in (baseline, candidate) for path, text in files.items())): + 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 +180,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 +199,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..afdcb889 100644 --- a/harnessgrad/personal/service.py +++ b/harnessgrad/personal/service.py @@ -2,12 +2,14 @@ from __future__ import annotations from pathlib import Path +from dataclasses import asdict import os import stat from harnessgrad.personal.adapters.codex import CodexAdapter from harnessgrad.personal.contracts import decode, source_events from harnessgrad.personal.event_store import EventStore +from harnessgrad.personal.evolution_service import PersonalEvolution from harnessgrad.personal.inputs import PersonalFeedback from harnessgrad.personal.profile import ModelSettings from harnessgrad.personal.proposal_jobs import INSTRUCTION, ProposalWorker @@ -29,7 +31,9 @@ def state_directory(path: Path) -> 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'): + for name in ('personal.sqlite3', 'personal.sqlite3-wal', 'personal.sqlite3-shm', + 'evolution.sqlite3', 'evolution.sqlite3-wal', 'evolution.sqlite3-shm', + 'connection.json'): target = root / name if target.exists() and (target.is_symlink() or target.stat().st_nlink != 1 or not target.is_file()): raise ValueError('personal state files must be ordinary single-link files') @@ -60,12 +64,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 @@ -117,14 +126,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/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_service.py b/tests/quality/test_personal_evolution_service.py new file mode 100644 index 00000000..5b56fe8a --- /dev/null +++ b/tests/quality/test_personal_evolution_service.py @@ -0,0 +1,256 @@ +"""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.adapters import codex +from harnessgrad.personal.adapters.contracts import HostBinding, TargetSelection +from harnessgrad.personal.api import PersonalServer +from harnessgrad.personal.contracts import SurfaceRef +from harnessgrad.personal.evolution_contracts import CandidateRequest, 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 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_text(text, encoding='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: + assert request(proposal_path, {})[0] == 200 + deadline = time.monotonic() + 8 + while time.monotonic() < deadline: + proposal = request(proposal_path)[1]['proposal'] + if proposal['status'] == 'ready': + break + time.sleep(.02) + else: + pytest.fail('proposal did not become ready') + 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_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.'} + 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(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'] From b64d27a8ac27b6ed98cbe8353843bb5aa39016ee Mon Sep 17 00:00:00 2001 From: trancefornow <2483151895@qq.com> Date: Tue, 1 Dec 2026 10:40:47 +0800 Subject: [PATCH 2/9] feat(personal): submit learning decisions to the C retest queue (cherry picked from commit 6acc6a3d38c7efab21b807053497ebe18858cd7a) --- docs/personal-evolution.md | 48 ++++ harnessgrad/personal/evolution_queue.py | 24 +- harnessgrad/personal/evolution_service.py | 11 +- .../personal/learning/reflection_store.py | 20 +- harnessgrad/personal/learning/submissions.py | 172 +++++++++++ harnessgrad/personal/learning_artifacts.py | 117 ++++++++ harnessgrad/personal/service.py | 39 ++- tests/quality/test_personal_learning_queue.py | 270 ++++++++++++++++++ 8 files changed, 692 insertions(+), 9 deletions(-) create mode 100644 harnessgrad/personal/learning/submissions.py create mode 100644 harnessgrad/personal/learning_artifacts.py create mode 100644 tests/quality/test_personal_learning_queue.py diff --git a/docs/personal-evolution.md b/docs/personal-evolution.md index 2b62ab36..2df7e684 100644 --- a/docs/personal-evolution.md +++ b/docs/personal-evolution.md @@ -313,3 +313,51 @@ 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" +``` diff --git a/harnessgrad/personal/evolution_queue.py b/harnessgrad/personal/evolution_queue.py index c232c87d..e1a97913 100644 --- a/harnessgrad/personal/evolution_queue.py +++ b/harnessgrad/personal/evolution_queue.py @@ -191,6 +191,18 @@ def open_question(self, job: JobRef, question_id: str, prompt: str) -> None: db.execute('INSERT OR IGNORE INTO evolution_questions VALUES (?,?,?,?,?,?,NULL)', (*job.scope.key(), job.job_id, question_id, prompt, 'open')) + 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) -> bool: identifier(question_id) if not isinstance(answer, str) or not answer.strip() or len(answer.encode('utf-8')) > 16384: @@ -250,11 +262,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: @@ -285,9 +299,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') diff --git a/harnessgrad/personal/evolution_service.py b/harnessgrad/personal/evolution_service.py index 6a7ce0d4..d1efcbc3 100644 --- a/harnessgrad/personal/evolution_service.py +++ b/harnessgrad/personal/evolution_service.py @@ -144,10 +144,16 @@ def _run(self, job: JobRef) -> None: self.queue.transition(job, 'retesting') revised = run_scenario(scenario, self.root, phase='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] self.queue.store.save_report(job, report.comparison_ref, { **asdict(report), 'job': asdict(job), 'snapshot_sha256': request.snapshot_sha256, 'candidate_id': request.candidate_ref, 'candidate_sha256': request.candidate_sha256, - 'verification': {'status': 'instruction_text_verified', 'label': '已验证指令文本', + 'verification': {'status': verification_status, 'label': label, 'later_behavior': 'unmeasured'}, }) self.queue.transition(job, report.status, reason_code=report.reason_code, @@ -247,5 +253,8 @@ def read_events(self, job: JobRef, *, after: int) -> EventPage: 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/reflection_store.py b/harnessgrad/personal/learning/reflection_store.py index 9085146c..84ad73c7 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, @@ -52,7 +53,24 @@ 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 lock(self, request: ReflectionInput): database = self.store.path.resolve() diff --git a/harnessgrad/personal/learning/submissions.py b/harnessgrad/personal/learning/submissions.py new file mode 100644 index 00000000..a45011ae --- /dev/null +++ b/harnessgrad/personal/learning/submissions.py @@ -0,0 +1,172 @@ +"""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 ( + EventPage, EvolutionQueuePort, JobRef, JobView, PortRejected, Scope, event_cursor, +) +from harnessgrad.personal.learning.extension_contracts import ComparisonReport, RunRecord +from harnessgrad.personal.learning.maintenance_contracts import MaintenanceArtifacts +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): + self.scope = scope + self.intake = intake + self.reflection = reflection + self.artifacts = artifacts + self.queue = queue + self.reports = reports + self.local_comparison = local_comparison + + 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 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.reflection.reflections.candidate_for_job(view.job) + if (not frozen 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 view.status in ('not_reproduced', 'retest_passed', 'retest_failed', 'not_comparable') + and 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.reflection.reflections.candidate_for_job(job) + if (frozen and 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 frozen and (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 report.reason_code == 'execution_timeout' + 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..b2988618 --- /dev/null +++ b/harnessgrad/personal/learning_artifacts.py @@ -0,0 +1,117 @@ +"""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 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 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/service.py b/harnessgrad/personal/service.py index afdcb889..aacec505 100644 --- a/harnessgrad/personal/service.py +++ b/harnessgrad/personal/service.py @@ -1,16 +1,27 @@ """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.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 @@ -26,14 +37,13 @@ def plain_directory(path: Path) -> Path: 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', - 'evolution.sqlite3', 'evolution.sqlite3-wal', 'evolution.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()): raise ValueError('personal state files must be ordinary single-link files') @@ -90,6 +100,27 @@ 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, + ) -> 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) + return LearningSubmissions(scope, intake, reflection, artifacts, queue, reports, + local_comparison=self.evolution.read_comparison) + def submit_feedback(self, value: dict) -> dict: return self.store.feedback.submit(PersonalFeedback.from_dict(value)) diff --git a/tests/quality/test_personal_learning_queue.py b/tests/quality/test_personal_learning_queue.py new file mode 100644 index 00000000..4b55c882 --- /dev/null +++ b/tests/quality/test_personal_learning_queue.py @@ -0,0 +1,270 @@ +"""D intake and reflection against disk-backed selected artifacts and the real C queue.""" +from __future__ import annotations + +from dataclasses import replace +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.learning.contracts import LearningPolicyUpdate +from harnessgrad.personal.learning.extension_contracts import ComparisonReport, RunRecord +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')) + + +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 + + +@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) From da32aa9d0740dc2b3c46cfee55f73b9adbfe9dfb Mon Sep 17 00:00:00 2001 From: trancefornow <2483151895@qq.com> Date: Tue, 1 Dec 2026 10:40:47 +0800 Subject: [PATCH 3/9] feat(personal): show and validate retest receipts in proposal history (cherry picked from commit 09f338b5506fa9d1df7eb3567f294ad470ef361b) --- console/static/personal-feedback.test.js | 23 +- console/static/personal-proposal.js | 50 +++- console/static/personal-review.js | 264 ++++++++++++++++++ console/static/personal-review.test.js | 198 +++++++++++++ console/static/personal.css | 20 ++ console/static/personal.html | 11 +- console/static/personal.js | 88 ++++-- docs/personal-evolution.md | 45 +++ harnessgrad/personal/api.py | 5 + harnessgrad/personal/proposal_run_store.py | 30 +- .../test_personal_evolution_service.py | 6 +- tests/quality/test_personal_proposal_flow.py | 5 + 12 files changed, 709 insertions(+), 36 deletions(-) create mode 100644 console/static/personal-review.js create mode 100644 console/static/personal-review.test.js diff --git a/console/static/personal-feedback.test.js b/console/static/personal-feedback.test.js index 903ffbae..e826262a 100644 --- a/console/static/personal-feedback.test.js +++ b/console/static/personal-feedback.test.js @@ -41,7 +41,7 @@ test('a different project stays independent; edits cannot replace a running requ assert.deepEqual(calls.map(call => call.project_id), ['one', 'two']); }); -async function page({failedHistory = false, readReceipt} = {}) { +async function page({failedHistory = false, readReceipt, history = [], saved = new Map()} = {}) { const nodes = new Map(), submitted = [], proposals = []; let generated = 0; function node(id) { if (!nodes.has(id)) nodes.set(id, { @@ -67,10 +67,10 @@ async function page({failedHistory = false, readReceipt} = {}) { } if (url.endsWith('/feedback')) { if (submitted.length && failedHistory) throw Error('list unavailable'); - return response({feedback: submitted.map(row => ({...row, id: 'recorded-id'}))}); + return response({feedback: [...history, ...submitted.map(row => ({...row, id: 'recorded-id'}))]}); } if (url.endsWith('/feedback/recorded-id')) { - const receipt = {...submitted[0], id: 'recorded-id'}; + const receipt = {...(history[0] || submitted[0]), id: 'recorded-id'}; return response(readReceipt ? await readReceipt(receipt) : receipt); } if (url.endsWith('/feedback/recorded-id/proposal')) { @@ -79,7 +79,8 @@ async function page({failedHistory = false, readReceipt} = {}) { } return response({revision:1}); }; - const storage = {getItem: () => null, removeItem() {}}; + const storage = {getItem: key => saved.get(key) ?? null, setItem: (key, value) => saved.set(key, value), + removeItem: key => saved.delete(key)}; vm.runInNewContext(fs.readFileSync(path.join(__dirname, 'personal.js'),'utf8'), { document, fetch, window: {HGPersonalDraft: require('./personal-draft.js'), HGPersonalWindow: require('./personal-window.js'), HGPersonalFeedback:{create}, HGPersonalProposal: require('./personal-proposal.js'), @@ -127,6 +128,20 @@ test('submission and history open the same proposal without creating a second ta assert.equal(ui.submitted.length, 1); }); +test('refresh reopens the selected feedback read-only and leaving the detail clears that selection', async () => { + const saved = new Map(), history = [{id: 'recorded-id', kind: 'explicit_request', text: 'Saved feedback', evidence: []}]; + const first = await page({saved, history}); + await first.node('feedback-history').children[0].children[1].onclick(); + const restored = await page({saved, history}); + assert.equal(restored.node('proposal-page').hidden, false); + assert.match(restored.node('proposal-feedback').textContent, /Saved feedback/); + assert.deepEqual(restored.proposals, ['GET']); + assert.deepEqual(restored.submitted, []); + await restored.node('proposal-records').onclick(); + const records = await page({saved, history}); + assert.deepEqual(records.proposals, []); +}); + for (const failed of [false, true]) { test(`collapsing ignores a late history ${failed ? 'error' : 'receipt'}`, async () => { let finishRead; diff --git a/console/static/personal-proposal.js b/console/static/personal-proposal.js index d2415b91..ca15e642 100644 --- a/console/static/personal-proposal.js +++ b/console/static/personal-proposal.js @@ -1,5 +1,6 @@ (function(root) { 'use strict'; + const review = typeof module !== 'undefined' && module.exports ? require('./personal-review') : root.HGPersonalReview; const active = new Set(['collecting', 'planning', 'proposing', 'checking']); const messages = { collecting: '正在读取项目指令', planning: '正在根据反馈制定计划', @@ -34,20 +35,27 @@ return current; } - function create({read, start, reply, cancel, updates, render, + function create({read, start, reply, cancel, updates, render, reviewApi, + reviewWait = () => new Promise(resolve => setTimeout(resolve, 1500)), wait = () => new Promise(resolve => setTimeout(resolve, 350))}) { let version = 0, controller; - function reset() { version++; controller?.abort(); render(null); } - async function open(project, feedback, action, initial = null) { + let pendingReply; + function stop() { version++; controller?.abort(); } + function reset() { stop(); pendingReply = undefined; render(null); } + async function open(project, feedback, action, initial = null, initialReview = null) { const current = ++version; controller?.abort(); const abort = controller = new AbortController(); let proposal = initial, after = 0, readFailures = 0; const display = (extra = {}) => render({project, feedback, proposal, ...extra}); - display({loading: true}); + display({loading: true, review: initialReview}); try { - ({proposal} = await action(project, feedback)); + ({proposal} = await action(project, feedback, abort.signal)); while (current === version) { + if (proposal?.feedback_id && proposal.feedback_id !== feedback) { + proposal = null; + throw Error('提案回执与当前反馈不匹配。'); + } display(); if (!active.has(proposal?.status)) break; if (updates) { @@ -57,20 +65,39 @@ } else await wait(); if (current !== version) break; try { - ({proposal} = await read(project, feedback)); + ({proposal} = await read(project, feedback, abort.signal)); readFailures = 0; } catch (error) { if (++readFailures >= 3) throw error; await wait(); } } + if (current === version && review.linkedJob(proposal?.result) && reviewApi) { + await review.watch({api: reviewApi, project, result: proposal.result, signal: abort.signal, + wait: reviewWait, display: value => { if (current === version) display({review: value}); }}); + } } catch (error) { - if (current === version) display({error: errors[error.code] || error.message}); + if (current === version) display({error: errors[error.code] || error.message, review: initialReview}); } } - return {reset, show: (project, feedback, generate = false) => open(project, feedback, generate ? start : read), + async function answerReview(project, feedback, proposal, question, answer, currentReview) { + const job = review.linkedJob(proposal.result); + const local = Boolean(proposal.result.evolution_job); + const key = JSON.stringify([job, question, answer]); + if (!pendingReply || pendingReply.key !== key) pendingReply = {key, id: 'reply_' + root.crypto.randomUUID()}; + await open(project, feedback, async (_id, _feedback, signal) => { + if (job.project_id !== project || job.profile_id !== 'default') throw Error('任务归属不匹配。'); + const payload = {question_id: question, answer}; + if (!local) payload.idempotency_key = pendingReply.id; + const view = await reviewApi(review.paths(job, local).task + '/reply', payload, {signal}); + if (!review.sameJob(view?.job, job)) throw Error('回复回执的任务归属不匹配。'); + if (!signal.aborted) pendingReply = undefined; + return {proposal}; + }, proposal, currentReview); + } + return {reset, stop, answerReview, show: (project, feedback, generate = false) => open(project, feedback, generate ? start : read), reply: (project, feedback, question, answer, current) => open(project, feedback, - (id, receipt) => reply(id, receipt, question, answer), current), + (id, receipt, signal) => reply(id, receipt, question, answer, signal), current), cancel: (project, feedback, current) => open(project, feedback, cancel, current)}; } @@ -106,6 +133,7 @@ return summary; } - if (typeof module !== 'undefined' && module.exports) module.exports = {create, describe, lastEventId, summarizeDiff}; - else root.HGPersonalProposal = {create, describe, summarizeDiff}; + const exported = {create, describe, lastEventId, summarizeDiff, renderReview: review.render, linkedJob: review.linkedJob}; + if (typeof module !== 'undefined' && module.exports) module.exports = exported; + else root.HGPersonalProposal = exported; })(typeof window === 'undefined' ? globalThis : window); diff --git a/console/static/personal-review.js b/console/static/personal-review.js new file mode 100644 index 00000000..51a2b55d --- /dev/null +++ b/console/static/personal-review.js @@ -0,0 +1,264 @@ +(function(root) { + 'use strict'; + const pending = new Set(['created', 'collecting', 'reproducing', 'baseline_ready', 'proposing', 'validating', 'retesting']); + const labels = { + needs_input: '等待补充信息', not_reproduced: '原版本未复现问题', not_comparable: '两次运行不可比', + retest_passed: '复测通过', retest_failed: '候选复测失败', no_change: '无需修改', + failed: '审核失败', interrupted: '审核已中断', cancelled: '审核已取消' + }; + const reasons = { + missing_evidence: '缺少判定所需的证据', execution_timeout: '运行超时', scenario_mismatch: '两次运行的场景或输入不一致', + stale_snapshot: '文件快照已变化', unstable_result: '多次尝试的结果不一致', budget_exhausted: '任务预算已用完', + runner_unavailable: '运行器不可用', scenario_unavailable: '场景不可用', candidate_failed: '候选未达到场景要求', + baseline_passed: '原版本已满足要求' + }; + class ReviewMismatch extends Error {} + function check(valid) { + if (!valid) throw new ReviewMismatch('回执与当前任务或冻结版本不匹配,请重新查看。'); + } + function id(value) { + check(typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value)); + return encodeURIComponent(value); + } + function sameJob(actual, expected) { + return actual?.job_id === expected.job_id && actual?.project_id === expected.project_id && + actual?.profile_id === expected.profile_id; + } + function paths(job, local = false) { + if (local) return {task: 'projects/' + id(job.project_id) + '/evolution/' + id(job.job_id)}; + const scope = 'evolution/v1/profiles/' + id(job.profile_id) + '/projects/' + id(job.project_id); + return {scope, task: scope + '/jobs/' + id(job.job_id)}; + } + function linkedJob(result) { return result?.evolution_job ?? result?.job_ref; } + function reason(code) { return reasons[code] || (typeof code === 'string' ? code : ''); } + function supportsRetestPass(run) { + const candidate = run.phase === 'candidate'; + if (run.judge_result !== (candidate ? 'met' : 'not_met')) return false; + if (run.scenario_id !== 'python-related-tests') return true; + return Number.isInteger(run.exit_code) && ((run.exit_code === 0) === candidate); + } + function verdict(view, report, runs) { + if ([view.reason_code, report?.reason_code].includes('execution_timeout') || + runs.some(row => row.status === 'timeout' || row.reason_code === 'execution_timeout')) return '运行超时'; + if (report?.verdict === 'retest_passed' && runs.every(row => row.scenario_id === 'python-related-tests')) + return '复测通过 · 已验证指令文本'; + if (report) return labels[report.verdict] || '报告结论待确认'; + if (pending.has(view.status) || view.status === 'retest_passed') return '等待复测报告'; + return labels[view.status] || '审核状态待确认'; + } + + async function localDetails(api, job, view, result, signal) { + const {task} = paths(job, true); + const review = {job, title: verdict(view, null, []), reason: reason(view.reason_code), + original: result.original_text, adoption: '尚无采用回执'}; + if (view.status === 'needs_input' && view.question_id) { + const question = await api(task + '/questions/' + id(view.question_id), undefined, {signal}); + check(sameJob(question?.job, job) && question.question_id === view.question_id); + review.question = question; + } + if (!view.comparison_ref) return review; + const report = await api(task + '/comparisons/' + id(view.comparison_ref), undefined, {signal}); + check(sameJob(report?.job, job) && report.comparison_ref === view.comparison_ref && + report.status === view.status && view.candidate_id && report.candidate_id === view.candidate_id && + result.snapshot_sha256 && report.snapshot_sha256 === result.snapshot_sha256 && + result.candidate_sha256 && report.candidate_sha256 === result.candidate_sha256); + const runs = ['baseline', 'candidate'].map(phase => { + const run = report[phase]; + check(run?.phase === phase && run.run_ref && report.scenario_id && run.scenario_id === report.scenario_id); + const executed = Number.isInteger(run.exit_code) && run.timed_out === false && !run.reason_code; + return {...run, status: run.timed_out ? 'timeout' : (executed ? 'executed' : 'failed'), + judge_result: executed ? (run.exit_code === 0 ? 'met' : 'not_met') : 'unknown', + log: {text: [run.stdout, run.stderr].filter(Boolean).join('\n'), truncated: run.output_truncated}}; + }); + const [before, after] = runs; + check(before.run_ref !== after.run_ref); + if (report.status === 'retest_passed') { + check(report.comparable === true && before.judge_result === 'not_met' && after.judge_result === 'met' && + before.source_unchanged === true && after.source_unchanged === true && Array.isArray(before.command) && + before.command.length && JSON.stringify(before.command) === JSON.stringify(after.command)); + } + const summary = {...report, report_ref: report.comparison_ref, verdict: report.status, fixture: result.fixture}; + return {...review, title: verdict(view, summary, runs), reason: reason(report.reason_code || view.reason_code), + runs, report: summary}; + } + + async function details(api, job, view, result, signal) { + const {scope, task} = paths(job); + const get = path => { + signal.throwIfAborted(); + return api(path, undefined, {signal}); + }; + async function artifact(ref, kind) { + const item = await get(scope + '/artifacts/' + id(ref) + '?kind=' + kind); + check(item?.ref === ref && item.kind === kind); + return item; + } + let original, candidate, report, question, adoption = '尚无采用回执'; + const runs = []; + if (view.candidate_id) { + candidate = await get(task + '/candidates/' + id(view.candidate_id)); + check(sameJob(candidate?.job, job) && candidate.candidate_id === view.candidate_id && + typeof result.snapshot_sha256 === 'string' && candidate.snapshot_sha256 === result.snapshot_sha256); + if (result.candidate_sha256) check(result.candidate_sha256 === candidate.candidate_sha256); + else check(candidate.diff_ref); + const snapshot = await artifact(candidate.snapshot_ref, 'virtual_snapshot'); + check(snapshot.sha256 === candidate.snapshot_sha256 && !snapshot.truncated); + original = snapshot.payload?.files?.['instruction.md']; + check(typeof original === 'string'); + if (typeof result.original_text === 'string') check(original === result.original_text); + if (!result.candidate_sha256) { + const diff = await artifact(candidate.diff_ref, 'diff'); + check(!diff.truncated && diff.payload?.text === result.diff); + } + } + if (view.question_id && view.status === 'needs_input') { + question = await get(task + '/questions/' + id(view.question_id)); + check(question?.question_id === view.question_id && (!question.job || sameJob(question.job, job))); + } + if (view.comparison_ref) { + report = await get(task + '/reports/' + id(view.comparison_ref)); + check(sameJob(report?.job, job) && report.report_ref === view.comparison_ref && + (!report.candidate_id || report.candidate_id === view.candidate_id) && + (!report.candidate_sha256 || report.candidate_sha256 === candidate?.candidate_sha256) && + (!['not_reproduced', 'not_comparable', 'retest_failed', 'retest_passed'].includes(view.status) || + view.status === report.verdict)); + const seen = new Set(); + for (const phase of ['baseline', 'candidate']) { + const refs = report[phase + '_run_refs']; + check(Array.isArray(refs) && refs.length <= 3); + for (const ref of refs) { + check(!seen.has(ref)); seen.add(ref); + const run = await get(task + '/runs/' + id(ref)); + check(sameJob(run?.job, job) && run.run_ref === ref && run.phase === phase && + run.snapshot_sha256 === result.snapshot_sha256 && run.fixture === report.fixture); + let log; + if (run.log_ref) { + const item = await artifact(run.log_ref, 'run_log'); + check(typeof item.payload?.text === 'string'); + log = {text: item.payload.text, truncated: item.truncated || run.log_truncated}; + } + runs.push({...run, log}); + } + } + if (report.verdict === 'retest_passed') { + const first = runs[0]; + check(candidate && report.candidate_id === candidate.candidate_id && report.comparable === true && + report.baseline_run_refs.length && report.candidate_run_refs.length && + runs.every(row => row.status === 'executed' && supportsRetestPass(row) && + row.scenario_id && row.scenario_sha256 && + row.scenario_id === first.scenario_id && row.scenario_sha256 === first.scenario_sha256 && + Array.isArray(row.command) && row.command.length && + JSON.stringify(row.command) === JSON.stringify(first.command) && + (row.phase !== 'candidate' || row.prepared_sha256 && + [candidate.candidate_sha256, result.prepared_sha256].includes(row.prepared_sha256)))); + } + } + const versionRef = result.version_receipt_ref || view.version_receipt_ref; + if (versionRef) { + const receipt = await get(task + '/receipts/' + id(versionRef)); + check(sameJob(receipt?.operation?.job, job) && receipt.receipt_ref === versionRef && + candidate && receipt.candidate_id === candidate.candidate_id && receipt.candidate_sha256 === candidate.candidate_sha256); + const entry = receipt.entries?.length === 1 && receipt.entries[0]; + const states = {applied: '已采用', rolled_back: '已回退', unchanged: '未改动', conflict: '采用时发生冲突', failed: '采用失败'}; + adoption = candidate.target_ids?.includes(entry?.target_id) && states[entry.status] || '采用回执待核对'; + } + return {job, title: verdict(view, report, runs), reason: reason(report?.reason_code || view.reason_code), + original: original ?? result.original_text, report, runs, question, adoption}; + } + + async function watch({api, project, result, signal, display, wait}) { + const job = linkedJob(result); + let after = 0, previous = '', pageFailures = 0, readFailures = 0; + try { + check(job.project_id === project && job.profile_id === 'default'); + const local = Boolean(result.evolution_job); + const {task} = paths(job, local); + while (!signal.aborted) { + let view; + try { + view = await api(task, undefined, {signal}); + readFailures = 0; + } catch (error) { + if (signal.aborted || ++readFailures >= 3) throw error; + await wait(); + continue; + } + check(sameJob(view?.job, job)); + const signature = JSON.stringify(view); + if (signature !== previous) { + const current = await (local ? localDetails : details)(api, job, view, result, signal); + if (signal.aborted) return; + display(current); previous = signature; + } + if (!pending.has(view.status) && !(view.status === 'retest_passed' && !view.comparison_ref)) return; + await wait(); + if (signal.aborted) return; + try { + const page = await api(task + '/events?after=' + after, undefined, {signal}); + let cursor = after; + check(Array.isArray(page.events)); + for (const event of page.events) { + check(sameJob(event?.job, job) && Number.isSafeInteger(event.seq) && event.seq > cursor); + cursor = event.seq; + } + check(page.next_after === cursor); + after = cursor; pageFailures = 0; + } catch (error) { + // A dropped event page leaves its cursor intact. Read the job again on reconnect. + if (error instanceof ReviewMismatch || ++pageFailures >= 3) throw error; + } + } + } catch (error) { + if (!signal.aborted) display({job: job.project_id === project && job.profile_id === 'default' ? job : null, + title: '复测报告暂不可用', error: error.message || '暂时无法读取复测报告。'}); + } + } + + function render(doc, review) { + const el = name => doc.getElementById('review-' + name); + el('section').hidden = !review; + if (!review) return; + el('title').textContent = review.title; + el('detail').textContent = [review.reason, review.error].filter(Boolean).join(' · '); + el('detail').hidden = !el('detail').textContent; + el('refs').hidden = !review.job; + el('refs').textContent = review.job ? [review.job.project_id, review.job.job_id, review.report?.report_ref].filter(Boolean).join(' / ') : ''; + el('adoption').textContent = review.adoption || ''; + el('fixture').hidden = review.report?.fixture !== true; + el('original').hidden = typeof review.original !== 'string'; + el('source').textContent = review.original ?? ''; + const question = review.question; + el('prompt').textContent = question?.prompt || ''; + el('prompt').hidden = !question?.prompt; + const block = (tag, text) => { + const element = doc.createElement(tag); + element.textContent = text; + return element; + }; + el('runs').replaceChildren(); + if (!review.report) return; + const judges = {met: '满足要求', not_met: '未满足要求', unknown: '未判定'}; + for (const phase of ['baseline', 'candidate']) { + const section = doc.createElement('section'); + section.append(block('h4', phase === 'baseline' ? '原版本运行' : '候选运行')); + const rows = review.runs.filter(row => row.phase === phase); + if (!rows.length) section.append(block('p', '没有运行记录')); + for (const row of rows) { + if (rows.length > 1) section.append(block('strong', '第 ' + row.attempt + ' 次尝试')); + section.append(block('p', [row.scenario_id || '场景未记录', + Number.isInteger(row.exit_code) ? '退出码 ' + row.exit_code : '无退出码', + judges[row.judge_result] || '判定未知'].join(' · '))); + const command = Array.isArray(row.command) && row.command.map(arg => + /[\s"']/.test(arg) ? JSON.stringify(arg) : arg).join(' '); + section.append(block('small', '执行命令'), block('pre', command || '无命令记录')); + if (row.reason_code) section.append(block('p', reason(row.reason_code))); + section.append(block('small', '运行证据'), block('pre', row.log?.text || (row.log ? '日志为空' : '无日志记录'))); + if (row.log?.truncated) section.append(block('small', '日志已截断')); + } + el('runs').append(section); + } + } + const exported = {watch, render, paths, sameJob, linkedJob}; + if (typeof module !== 'undefined' && module.exports) module.exports = exported; + else root.HGPersonalReview = exported; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/console/static/personal-review.test.js b/console/static/personal-review.test.js new file mode 100644 index 00000000..9266c5a6 --- /dev/null +++ b/console/static/personal-review.test.js @@ -0,0 +1,198 @@ +'use strict'; +const assert = require('node:assert/strict'); +const test = require('node:test'); +const {create} = require('./personal-proposal'); +const {watch, paths} = require('./personal-review'); + +const job = {profile_id: 'default', project_id: 'project-a', job_id: 'evo-one'}; +const {scope, task} = paths(job); +const result = {job_ref: job, snapshot_sha256: 'a'.repeat(64), candidate_sha256: 'b'.repeat(64), diff: '+new'}; +function fixture() { + const view = {job, status: 'retest_passed', candidate_id: 'cand', comparison_ref: 'report'}; + const report = {report_ref: 'report', job, candidate_id: 'cand', comparable: true, verdict: view.status, + baseline_run_refs: ['r1'], candidate_run_refs: ['r2'], fixture: true}; + const data = new Map([[task, view], [task + '/reports/report', report], + [task + '/candidates/cand', {job, candidate_id: 'cand', snapshot_ref: 'snap', target_ids: ['project-instructions'], + snapshot_sha256: result.snapshot_sha256, candidate_sha256: result.candidate_sha256}], + [scope + '/artifacts/snap?kind=virtual_snapshot', {kind: 'virtual_snapshot', ref: 'snap', + sha256: result.snapshot_sha256, payload: {files: {'instruction.md': 'before'}}}]]); + for (const [index, phase] of ['baseline', 'candidate'].entries()) { + const ref = 'r' + (index + 1), log = 'log' + index; + data.set(task + '/runs/' + ref, {job, run_ref: ref, phase, scenario_id: 'python-related-tests', + scenario_sha256: 'c'.repeat(64), snapshot_sha256: result.snapshot_sha256, fixture: true, + command: ['python', 'check.py'], log_ref: log, prepared_sha256: index ? result.candidate_sha256 : null, + exit_code: index ? 0 : 1, judge_result: index ? 'met' : 'not_met', status: 'executed'}); + data.set(scope + '/artifacts/' + log + '?kind=run_log', {ref: log, kind: 'run_log', payload: {text: phase}}); + } + return {view, report, data, api: async (path, value) => { + assert.equal(value, undefined); assert.ok(data.has(path), path); return data.get(path); + }}; +} +async function read(f, options = {}) { + const output = []; + await watch({project: job.project_id, result, api: f.api, signal: new AbortController().signal, + display: value => output.push(value), wait: async () => {}, ...options}); + return output.at(-1); +} + +test('reads the frozen original, both scoped runs and logs before reporting a text-only pass', async () => { + const value = await read(fixture()); + assert.equal(value.title, '复测通过 · 已验证指令文本'); + assert.equal(value.original, 'before'); + assert.deepEqual(value.runs.map(r => [r.exit_code, r.log.text]), [[1, 'baseline'], [0, 'candidate']]); + assert.equal(value.adoption, '尚无采用回执'); +}); + +test('a v1 text pass requires every baseline to fail and every candidate to pass', async () => { + for (const [ref, exit_code, judge_result] of [ + ['r1', 0, 'met'], ['r1', 0, 'not_met'], ['r1', 1, 'unknown'], + ['r1', null, 'not_met'], ['r2', 1, 'met'], ['r2', null, 'met'], + ]) { + const f = fixture(); + const run = f.data.get(task + '/runs/' + ref); + f.report[run.phase + '_run_refs'].push('retry'); + f.data.set(task + '/runs/retry', {...run, run_ref: 'retry', exit_code, judge_result}); + const value = await read(f); + assert.equal(value.title, '复测报告暂不可用'); + assert.ok(value.error); + assert.equal(value.report, undefined); + } +}); + +test('two successful v1 runs support not_reproduced but cannot support retest_passed', async () => { + const f = fixture(); + Object.assign(f.data.get(task + '/runs/r1'), {exit_code: 0, judge_result: 'met'}); + assert.ok((await read(f)).error); + f.view.status = f.report.verdict = 'not_reproduced'; + f.report.reason_code = 'baseline_passed'; + const value = await read(f); + assert.equal(value.title, '原版本未复现问题'); + assert.equal(value.reason, '原版本已满足要求'); +}); + +test('the local worker report is tied to the B snapshot and reads both embedded runs', async () => { + const ref = 'comparison-one', path = 'projects/project-a/evolution/evo-one'; + const local = {evolution_job: job, snapshot_sha256: result.snapshot_sha256, candidate_sha256: result.candidate_sha256}; + const run = {scenario_id: 'python-related-tests', source_unchanged: true, timed_out: false, command: ['python', 'check.py']}; + const report = {comparison_ref: ref, scenario_id: run.scenario_id, candidate_id: 'c', job, + snapshot_sha256: local.snapshot_sha256, candidate_sha256: local.candidate_sha256, status: 'retest_passed', + comparable: true, baseline: {...run, phase: 'baseline', run_ref: 'r1', exit_code: 1, stderr: 'rule missing'}, + candidate: {...run, phase: 'candidate', run_ref: 'r2', exit_code: 0, stderr: 'OK'}}; + const api = async (url, value) => { + assert.equal(value, undefined); + if (url === path) return {job, candidate_id: 'c', comparison_ref: ref, status: report.status}; + assert.equal(url, path + '/comparisons/' + ref); + return report; + }; + const load = () => read({api}, {result: local}); + const success = await load(); + assert.equal(success.title, '复测通过 · 已验证指令文本'); + assert.deepEqual(success.runs.map(row => row.log.text), ['rule missing', 'OK']); + report.candidate.exit_code = 1; + assert.ok((await load()).error); + report.status = 'retest_failed'; + assert.equal((await load()).title, '候选复测失败'); + report.snapshot_sha256 = 'other'; + assert.ok((await load()).error); +}); + +test('requires matching job, snapshot, candidate, run and artifact identities', async () => { + for (const change of [ + f => { f.view.job = {...job, project_id: 'b'}; }, + f => { f.data.get(task + '/candidates/cand').candidate_sha256 = 'wrong'; }, + f => { f.report.job = {...job, job_id: 'another'}; }, + f => { f.data.get(task + '/runs/r1').phase = 'candidate'; }, + f => { f.data.get(task + '/runs/r1').snapshot_sha256 = 'wrong'; }, + f => { f.data.get(scope + '/artifacts/log0?kind=run_log').ref = 'other'; }, + f => { f.report.candidate_run_refs = []; }, + f => { f.data.get(task + '/runs/r2').command = ['another']; }, + ]) { + const f = fixture(); change(f); + const value = await read(f); assert.ok(value.error); assert.equal(value.report, undefined); + } + let calls = 0; + const foreign = await read(fixture(), {project: 'b', api: () => calls++}); + assert.equal(calls, 0); assert.equal(foreign.job, null); +}); + +test('shows verdicts, the actual reason and the scoped version receipt independently', async () => { + for (const [status, code, title] of [ + ['not_reproduced', 'baseline_passed', '原版本未复现问题'], ['retest_failed', 'candidate_failed', '候选复测失败'], + ['not_comparable', 'scenario_mismatch', '两次运行不可比'], ['not_comparable', 'execution_timeout', '运行超时'], + ['not_comparable', 'future_reason', '两次运行不可比'] + ]) { + const f = fixture(); + f.report.verdict = f.view.status = status; f.report.reason_code = code; + const value = await read(f); assert.equal(value.title, title); assert.ok(value.reason); + } + const f = fixture(); + f.view.version_receipt_ref = 'v1'; + const receipt = {receipt_ref: 'v1', operation: {job}, candidate_id: 'cand', candidate_sha256: result.candidate_sha256, + entries: [{target_id: 'project-instructions', status: 'applied'}]}; + f.data.set(task + '/receipts/v1', receipt); + assert.equal((await read(f)).adoption, '已采用'); + receipt.operation.job = {...job, job_id: 'other'}; + assert.ok((await read(f)).error); +}); + +test('resumes C pages independently of proposal SSE and re-reads the completed job', async () => { + const f = fixture(), cursors = [], b = [], seen = []; + let reads = 0; + const controller = create({read: async () => ({proposal: ++reads === 1 ? {status: 'checking'} : {status: 'ready', result}}), + updates: async (_p, _f, after) => { b.push(after); return 'id: 19\n\n'; }, + reviewApi: async (path, value) => { + if (path === task && cursors.length < 3) return {job, status: 'collecting'}; + if (path.includes('/events?')) { + cursors.push(path.split('=').pop()); + if (cursors.length === 2) throw Error('disconnected'); + const seq = cursors.length; return {events: [{seq, job}], next_after: seq}; + } + return f.api(path, value); + }, render: state => seen.push(state), reviewWait: async () => {}}); + await controller.show(job.project_id, 'feedback'); + assert.deepEqual(b, [0]); assert.deepEqual(cursors, ['0', '1', '1']); + assert.ok(seen.some(s => s.review?.title === '等待复测报告')); + assert.equal(seen.at(-1).review.report.report_ref, 'report'); +}); + +test('an open C question sends the scoped reply and retries a lost acknowledgement using the same key', async () => { + const f = fixture(), writes = [], seen = []; + const proposal = {status: 'ready', result}; + let answered = false; + const controller = create({read: async () => ({proposal}), render: state => seen.push(state), + reviewApi: async (path, value) => { + if (path === task && !answered) return {job, status: 'needs_input', question_id: 'q'}; + if (path.endsWith('/questions/q')) return {question_id: 'q', prompt: '哪项测试?', open: true}; + if (path.endsWith('/reply')) { + writes.push(value); + if (writes.length === 1) throw Error('lost reply'); + answered = true; return f.view; + } + return f.api(path, value); + }}); + await controller.show(job.project_id, 'feedback'); + assert.equal(seen.at(-1).review.question.prompt, '哪项测试?'); + for (let i = 0; i < 2; i++) await controller.answerReview(job.project_id, 'feedback', proposal, 'q', 'pytest'); + assert.deepEqual(writes[0], writes[1]); assert.ok(writes[0].idempotency_key); + assert.equal(seen.at(-1).review.job.job_id, job.job_id); +}); + +test('switching projects or closing during a report read suppresses the late response', async () => { + for (const change of ['switch', 'close']) { + let release, began; + const reading = new Promise(resolve => { began = resolve; }); + const seen = [], f = fixture(); + const controller = create({read: async project => ({proposal: project === 'b' ? null : {status: 'ready', result}}), + render: state => seen.push(state), reviewApi: async (path, value, {signal}) => { + if (path.endsWith('/reports/report')) { + began(signal); await new Promise(resolve => { release = resolve; }); + } + return f.api(path, value); + }}); + const showing = controller.show(job.project_id, 'feedback'), signal = await reading; + if (change === 'switch') await controller.show('b', 'feedback-b'); else controller.stop(); + const count = seen.length; + release(); await showing; + assert.equal(signal.aborted, true); assert.equal(seen.length, count); + } +}); diff --git a/console/static/personal.css b/console/static/personal.css index fbf17890..63a79a41 100644 --- a/console/static/personal.css +++ b/console/static/personal.css @@ -239,6 +239,26 @@ body[data-mode="details"][data-view="proposal"] .composer { display: none; } .proposal-approval { margin-top: 14px; text-align: center; } .proposal-approval button { width: 100%; white-space: normal; } .proposal-approval p { margin-bottom: 0; } +.review-report { border-top: 1px solid var(--hg-alias-border-l2); margin: 16px 0; padding-top: 14px; } +.review-report h3, .review-report h4 { margin: 0; } +.review-report h3 { font-size: 15px; } +.review-report .badge { color: var(--hg-alias-brand-text); font-size: 11px; } +.review-report h4 { font-size: 13px; } +.review-outcome { display: flex; flex-wrap: wrap; gap: 4px 12px; align-items: baseline; margin: 6px 0; } +.review-outcome strong { color: var(--hg-alias-brand-text); } +.review-outcome span, .review-report details, .review-report p { font-size: 12px; } +.review-report details { margin: 8px 0; } +.review-report summary { cursor: pointer; } +.review-report pre { + white-space: pre-wrap; overflow-wrap: anywhere; max-height: 14rem; overflow: auto; + margin: 6px 0; padding: 7px 9px; background: var(--hg-alias-bg-layer-2); + border-radius: 6px; font: 12px/1.55 ui-monospace, monospace; +} +#review-runs { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 205px), 1fr)); gap: 12px; } +#review-runs section { min-width: 0; padding-top: 7px; } +#review-runs small { display: block; margin-top: 6px; color: var(--hg-alias-label-primary); } +#review-runs pre { margin-top: 2px; } +.review-report p { margin: 4px 0; overflow-wrap: anywhere; } @media (max-width: 460px) { body:not(.desktop) { padding: 12px; } } diff --git a/console/static/personal.html b/console/static/personal.html index 8aa85eb6..24741e84 100644 --- a/console/static/personal.html +++ b/console/static/personal.html @@ -1,5 +1,5 @@ -HarnessGrad · 个人持续进化 +HarnessGrad · 个人持续进化
@@ -94,6 +94,15 @@

把这次反馈,变成下次的习惯< 查看修改前后的差异

           
+