diff --git a/doc/agents/one-queue-claiming-work.md b/doc/agents/one-queue-claiming-work.md index df5d3291dc..90685558ba 100644 --- a/doc/agents/one-queue-claiming-work.md +++ b/doc/agents/one-queue-claiming-work.md @@ -58,3 +58,24 @@ work** — the same PR, or the same run for non-PR work. Editing this file without that record is an incomplete change, and a change that contradicts an accepted record must supersede it rather than diverge from it in silence. + +## Implementation target and usable work window (2026-11-18) + +`payload.repo` identifies the tracking issue's repository. When implementation +belongs elsewhere, producers set `payload.implementation_repo` to its explicit +`owner/name`. `--filter 'repo = code'` and `repo != code` select that implementation +target first, falling back to the tracking repo for ordinary legacy packets. +Issue references and duplicate-work identity continue to use the tracking repo. +A packet explicitly flagged `cross-repo-change` without this target is quarantined +at claim time with a repair reason, not handed to another mismatched worker. +Never infer the target from a title, or use an enqueue dedupe hit as a packet edit. + +For a bounded session, pass `--remaining-budget-minutes ` on EACH +claim, recomputing the remaining usable work window rather than passing the whole +initial window repeatedly. Producers declare `required_budget_minutes` for the +minimum uninterrupted time to the next safe checkpoint. Existing broker matching +excludes requirement-bearing tasks unless the declared remaining window fits; +a fitting worker can bypass a capacity park's timer. `timebox_minutes` is NOT an +estimate or a requirement. Do not invent an hours requirement from `effort/l`. +Ownership/handoff holds remain independent: a longer budget is not authorization. +See [FDR-0011](../decisions/FDR-0011-implementation-target-and-work-window.md). diff --git a/doc/decisions/FDR-0011-implementation-target-and-work-window.md b/doc/decisions/FDR-0011-implementation-target-and-work-window.md new file mode 100644 index 0000000000..472b4d5e20 --- /dev/null +++ b/doc/decisions/FDR-0011-implementation-target-and-work-window.md @@ -0,0 +1,55 @@ +# FDR-0011: Implementation target and usable work window + +- Date: 2026-11-18 +- Status: accepted +- Owner: Fleet queue maintainers +- Decision maker: Drew, explicit request to filter Fleet claims by actual implementation repository and suitable work window, 2026-11-18. + +## Context and sources + +Task 20592 tracks [code#10415](https://github.com/developing-today/code/issues/10415) +but explicitly implements a workflow in developing-today/kaneo. Its packet says +`repo=developing-today/code` and `risk.flags=[cross-repo-change]`; code-only workers +repeatedly claim and park it. Tasks 20725/#7587 and 20567/#10345 have 45-minute +timeboxes but no structured required budget, and their checkpoints also require +owner handoff. Those facts do not establish a numeric effort estimate or release. +Existing #3418 already implements required/remaining-budget matching. + +## Options and decision + +Keep the status quo, infer targets/durations from prose, or introduce explicit +implementation metadata and reuse the existing budget contract. Choose the last: +optional validated `payload.implementation_repo` (owner/name) takes precedence in +claim repo filters. Tracking repo, issue references, and work dedupe are unchanged. +Ordinary legacy packets retain their prior matching. Explicitly cross-repo packets +without a target fail closed at the claim payload guard with a repair diagnostic. + +Bounded callers declare their current usable remaining window on each claim via +`--remaining-budget-minutes`; packets use `required_budget_minutes` for the minimum +uninterrupted checkpoint window. Retain #3418's gate, capacity timer bypass, and +manual/handoff semantics. Do not repurpose timebox or infer hours from effort/l. + +## Consequences and verification + +SQL and pure filter tests must agree for tracking-code/implementation-Kaneo, legacy +fallback, and negated filters. Validation rejects malformed targets. Synthetic SQL +checks exercise target selection together with the existing budget gate, including +exact boundary, too-short, absent budget, and requirement-free legacy work. + +This code does not deploy the broker, change scheduled prompts, or repair stored +packets. Current broker has no supported payload edit verb; an enqueue dedupe hit +is not a repair. Explicit cross-repo packets may become quarantined until repaired. +Reconcile those diagnostics and provide a guarded packet-repair path; never edit +live task SQL or bypass ownership to make a demonstration pass. + +## Revisit + +Revisit if work requires multiple implementation repositories or measured metadata +shows a single target insufficient. Do not treat a tracking repo or prose guess as +proof. No prior accepted FDR is superseded; this refines #8097's repo dimension and +uses #3418's budget contract. FDR-0002 manual overrides remain unchanged. + +## Open questions + +Legacy capacity and ownership records need producer-verified metadata. Default: +leave their holds unchanged; no guessed duration, inferred release, or deployment. diff --git a/doc/decisions/README.md b/doc/decisions/README.md index 60c4ae06f5..b267e3caeb 100644 --- a/doc/decisions/README.md +++ b/doc/decisions/README.md @@ -166,6 +166,8 @@ the decision; `Implementation` is where the decision lands in code, docs, or iss | [FDR-0009](FDR-0009-park-reboot-test.md) | A park that leaves its trigger unchanged fails the reboot test | `proposed` | Fleet queue maintainers | Drew's analysis of the #9155 stop, 2026-11-12 | [#9177](https://github.com/developing-today/code/issues/9177) stopper investigation; #9178 §2 boot behavior | | [FDR-0010](FDR-0010-completion-requires-evidence.md) | Issue completion requires deliverable evidence from the bound work | `proposed` | Fleet queue maintainers | Policy direction from the [#9155](https://github.com/developing-today/code/issues/9155) closure, 2026-11-12; prior pattern [#7610](https://github.com/developing-today/code/issues/7610) | [#9221](https://github.com/developing-today/code/issues/9221) closure records + reason-required closes; [#9177](https://github.com/developing-today/code/issues/9177) | +| [FDR-0011](FDR-0011-implementation-target-and-work-window.md) | Implementation target and usable work window | `accepted` | Fleet queue maintainers | Drew request, 2026-11-18; code#10415/task 20592 | Claim repo filter + existing #3418 budget gate | + ### Package-scoped records (not in this namespace) | Namespace | Records | Status | Owner | Notes | diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs index 4ba968b9cc..f2aecdd7f4 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs @@ -3648,6 +3648,57 @@ mod tests { ); } + #[test] + fn implementation_repo_sql_and_budget_matrix() { + // Oracle: execute production expressions in isolated SQLite against a model. + let output = std::process::Command::new("python3") + .arg(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/implementation_repo_sql.py" + )) + .output() + .expect("claim SQL tests require Python 3 with stdlib sqlite3"); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + } + + #[test] + fn implementation_repo_filters_work_not_tracking_issue() { + // Oracle: issue #10415 lives in code, but its deliverable is in Kaneo. + // Tracking/dedupe identity must remain code; claim eligibility must not. + let row = json!({"queue":"repo-health-code-pilot", "payload": { + "repo":"developing-today/code", "implementation_repo":"developing-today/kaneo", + "kind":"small_fix", "issue":{"number":10415} + }}); + assert!(!filter_matches(&parse_filter("repo = code").unwrap(), &row)); + assert!(filter_matches(&parse_filter("repo = kaneo").unwrap(), &row)); + assert!(filter_matches(&parse_filter("repo != code").unwrap(), &row)); + let encoded = + json!({"queue":"repo-health-code-pilot", "payload":row["payload"].to_string()}); + assert!(filter_matches( + &parse_filter("repo = kaneo").unwrap(), + &encoded + )); + assert_eq!(task_repo_identity(&row), "developing-today/code"); + assert_eq!(work_identity(&row).unwrap().repo, "developing-today/code"); + let unknown = json!({"payload":{"repo":"developing-today/code", "risk":{"flags":["cross-repo-change"]}}}); + assert!( + claim_guard_reason(&unknown) + .unwrap() + .contains("implementation_repo") + ); + let legacy = + json!({"queue":"repo-health-code-pilot", "payload":{"repo":"developing-today/code"}}); + assert!(filter_matches( + &parse_filter("repo = code").unwrap(), + &legacy + )); + } + #[test] fn one_queue_task_requirements_match_claimers_automatically_8097() { // A task's own declared requirements are honored inside diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue/claim.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue/claim.rs index 2b3405fd90..6dcfb8aaa1 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue/claim.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue/claim.rs @@ -1625,9 +1625,10 @@ pub(crate) fn validate_filter(expr: &FilterExpr) -> Result<(), String> { } } -/// SQL for the task's repo identity (see the section comment): -/// the payload's declared repo, else the stream-derived repo. -pub(crate) const REPO_IDENTITY_SQL: &str = "COALESCE(NULLIF(json_extract(payload, '$.repo'), ''), \ +// A tracking issue may live in code while its deliverable lives elsewhere. +// Keep tracking identity (and work-identity dedupe) separate from eligibility. +pub(crate) const IMPLEMENTATION_REPO_SQL: &str = "COALESCE(NULLIF(json_extract(payload, '$.implementation_repo'), ''), \ + NULLIF(json_extract(payload, '$.repo'), ''), \ CASE WHEN queue LIKE 'repo-health-%' \ THEN replace(replace(replace(queue, 'repo-health-', ''), '-pilot', ''), '-shadow', '') \ ELSE queue END)"; @@ -1635,7 +1636,7 @@ pub(crate) const REPO_IDENTITY_SQL: &str = "COALESCE(NULLIF(json_extract(payload pub(crate) fn repo_eq_sql(v: &str, args: &mut Vec) -> String { args.push(Arg::Text(v.to_string())); args.push(Arg::Text(v.to_string())); - format!("({REPO_IDENTITY_SQL} = ? OR {REPO_IDENTITY_SQL} LIKE '%/' || ?)") + format!("({IMPLEMENTATION_REPO_SQL} = ? OR {IMPLEMENTATION_REPO_SQL} LIKE '%/' || ?)") } pub(crate) fn label_eq_sql(v: &str, args: &mut Vec) -> String { @@ -1880,7 +1881,7 @@ pub(crate) fn task_payload(row: &Value) -> Value { } } -/// The task's repo identity (mirrors REPO_IDENTITY_SQL): the +/// The task's tracking repo identity (not implementation eligibility): the /// payload's declared repo when present and non-empty, else the /// stream name with the repo-health- prefix and -pilot / -shadow /// suffixes stripped. @@ -1898,6 +1899,16 @@ pub fn task_repo_identity(row: &Value) -> String { } } +/// Claim filters use the explicit implementation target, not the issue host. +pub fn task_implementation_repo(row: &Value) -> String { + task_payload(row) + .get("implementation_repo") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .unwrap_or_else(|| task_repo_identity(row)) +} + pub(crate) fn repo_value_matches(identity: &str, value: &str) -> bool { identity == value || identity.ends_with(&format!("/{value}")) } @@ -1918,7 +1929,7 @@ pub(crate) fn cmp_matches(field: FilterField, op: CmpOp, values: &[String], row: let payload = task_payload(row); match field { FilterField::Repo => { - let identity = task_repo_identity(row); + let identity = task_implementation_repo(row); let any = values.iter().any(|v| repo_value_matches(&identity, v)); match op { CmpOp::Eq | CmpOp::In => any, diff --git a/pkgs/fleet/crates/fleet-queue/src/validate.rs b/pkgs/fleet/crates/fleet-queue/src/validate.rs index 42a3d0779d..d5a2e11bb7 100644 --- a/pkgs/fleet/crates/fleet-queue/src/validate.rs +++ b/pkgs/fleet/crates/fleet-queue/src/validate.rs @@ -110,6 +110,36 @@ fn manual_schema_errors(p: &Value) -> Vec { python_repr(get("repo")) )); } + // Do not accept a cross-repo task whose only identity is its issue host. + // Keep enqueue, claim quarantine and quarantine-recheck on one contract. + if get("implementation_repo").is_none() + && p.pointer("/risk/flags") + .and_then(Value::as_array) + .is_some_and(|flags| { + flags + .iter() + .any(|f| f.as_str() == Some("cross-repo-change")) + }) + { + errs.push("payload.implementation_repo: required for cross-repo-change; repair the explicit implementation target before claiming".to_string()); + } + if let Some(target) = get("implementation_repo") { + let valid = target.as_str().is_some_and(|s| { + let parts: Vec<_> = s.split('/').collect(); + parts.len() == 2 + && parts.iter().all(|part| { + !part.is_empty() + && *part != "." + && *part != ".." + && part + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) + }) + }); + if !valid { + errs.push("payload.implementation_repo: must be an owner/name repository".to_string()); + } + } for f in ["problem", "priority_reason"] { match get(f) { Some(Value::String(s)) if !s.is_empty() => {} @@ -1217,6 +1247,65 @@ mod tests { assert_eq!(task_from_packet(&packet, "q")["max_attempts"], 7); } + #[test] + fn implementation_repo_validates_explicit_target() { + // Oracle: an optional owner/name target, not an issue-repo allowlist. + let payload = payload_with( + json!({"issue":{"number":10415}, "risk":{"level":"low","flags":["cross-repo-change"]}}), + ); + let mut packet = json!({"title":"replicate workflow", "priority":30, "payload":payload, "dedupe_key":"repo-health:v1:fix:developing-today/code:issue:10415"}); + assert!( + validate_packet(&packet) + .0 + .iter() + .any(|e| e.contains("implementation_repo")) + ); + packet["payload"]["implementation_repo"] = json!("developing-today/kaneo"); + assert!( + validate_packet(&packet).0.is_empty(), + "{:?}", + validate_packet(&packet).0 + ); + let row = task_from_packet(&packet, "repo-health-code-pilot"); + assert!( + validate_packet(&row).0.is_empty(), + "{:?}", + validate_packet(&row).0 + ); + + let unknown = payload_with(json!({"risk":{"level":"low","flags":["cross-repo-change"]}})); + assert!( + manual_schema_errors(&unknown) + .iter() + .any(|e| e.contains("implementation_repo")) + ); + + for target in [json!("developing-today/kaneo"), json!("owner/repo.name-1")] { + let payload = payload_with(json!({"implementation_repo":target})); + assert!( + !manual_schema_errors(&payload) + .iter() + .any(|e| e.contains("implementation_repo")) + ); + } + for target in [ + json!(null), + json!(""), + json!("kaneo"), + json!("o/r/extra"), + json!(" o/r"), + json!(3), + ] { + let payload = payload_with(json!({"implementation_repo":target})); + assert!( + manual_schema_errors(&payload) + .iter() + .any(|e| e.contains("implementation_repo")), + "{target}" + ); + } + } + #[test] fn required_budget_minutes_validation_and_selection_3418() { // #3418 (#4712): optional at both levels; absent/null in both diff --git a/pkgs/fleet/crates/fleet-queue/tests/implementation_repo_sql.py b/pkgs/fleet/crates/fleet-queue/tests/implementation_repo_sql.py new file mode 100644 index 0000000000..d47cbbfb87 --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/tests/implementation_repo_sql.py @@ -0,0 +1,61 @@ +"""Oracle: production SQLite claim predicates select work target and fitting window. +In-memory only; no broker, credentials, or live claims. Uses production expressions, +not a second hand-written repo/budget selection algorithm. +""" +import itertools +import json +import pathlib +import re +import sqlite3 +import unittest + +SRC = (pathlib.Path(__file__).resolve().parents[1] / 'src/turso_queue/claim.rs').read_text() + + +def constant(name): + raw = re.search(r'const ' + name + r': &str = "(.*?)";', SRC, re.S).group(1) + return re.sub(r'\\\n\s*', '', raw).replace('\\"', '"') + + +def budget_gate(): + body = re.search(r'fn budget_gate_sql\(\).*?format!\("(.*?)"\)', SRC, re.S).group(1) + return body.replace('{REQUIRED_BUDGET_EXPR}', constant('REQUIRED_BUDGET_EXPR')) + + +class ImplementationRepoSQL(unittest.TestCase): + def test_target_and_budget_matrix(self): + # Model: an explicitly declared target overrides tracking, and a declared + # requirement fits iff the claimant provides at least that much time. + db = sqlite3.connect(':memory:') + db.execute('CREATE TABLE tasks(queue TEXT, payload TEXT, required_budget_minutes INTEGER)') + subject = constant('IMPLEMENTATION_REPO_SQL') + self.assertIn('{IMPLEMENTATION_REPO_SQL} = ?', SRC) + for target, requirement, remaining in itertools.product( + [None, 'developing-today/code', 'developing-today/kaneo'], + [None, 45, 180], [None, 30, 45, 179, 180, 240]): + payload = {'repo': 'developing-today/code'} + if target is not None: + payload['implementation_repo'] = target + if requirement is not None: + payload['required_budget_minutes'] = requirement + db.execute('DELETE FROM tasks') + db.execute('INSERT INTO tasks VALUES(?,?,NULL)', ('repo-health-code-pilot', json.dumps(payload))) + for repo in ['code', 'kaneo']: + actual = db.execute('SELECT COUNT(*) FROM tasks WHERE (' + subject + ' = ? OR ' + subject + " LIKE '%/' || ?) AND " + budget_gate(), (repo, repo, remaining)).fetchone()[0] + expected = (target or 'developing-today/code').endswith('/' + repo) and (requirement is None or (remaining is not None and remaining >= requirement)) + self.assertEqual(actual, int(expected), (target, requirement, remaining, repo)) + negated = db.execute('SELECT COUNT(*) FROM tasks WHERE NOT (' + subject + ' = ? OR ' + subject + " LIKE '%/' || ?) AND " + budget_gate(), (repo, repo, remaining)).fetchone()[0] + expected_not = not (target or 'developing-today/code').endswith('/' + repo) and (requirement is None or (remaining is not None and remaining >= requirement)) + self.assertEqual(negated, int(expected_not), (target, requirement, remaining, repo)) + + + def test_park_requirement_overrides_packet_requirement(self): + db = sqlite3.connect(':memory:') + db.execute('CREATE TABLE tasks(payload TEXT, required_budget_minutes INTEGER)') + db.execute('INSERT INTO tasks VALUES(?,180)', ('{"required_budget_minutes":45}',)) + for window, matches in [(45, 0), (179, 0), (180, 1)]: + self.assertEqual(db.execute('SELECT COUNT(*) FROM tasks WHERE ' + budget_gate(), (window,)).fetchone()[0], matches) + + +if __name__ == '__main__': + unittest.main() diff --git a/pkgs/fleet/repo-task-v1.schema.json b/pkgs/fleet/repo-task-v1.schema.json index 4279cdb80b..c6cf4d0e8c 100644 --- a/pkgs/fleet/repo-task-v1.schema.json +++ b/pkgs/fleet/repo-task-v1.schema.json @@ -1,6 +1,16 @@ { "$id": "repo-task/v1", "$schema": "https://json-schema.org/draft/2020-12/schema", + "allOf": [{ + "if": { + "required": ["risk"], + "properties": {"risk": { + "required": ["flags"], + "properties": {"flags": {"contains": {"const": "cross-repo-change"}}} + }} + }, + "then": {"required": ["implementation_repo"]} + }], "$defs": { "completion_telemetry": { "type": "object", @@ -73,6 +83,11 @@ }, "type": "array" }, + "implementation_repo": { + "description": "Repository receiving the implementation when different from the issue-tracking repo. Claim repo filters use this field first; issue/dedupe identity remains repo. Explicit owner/name, not a URL.", + "type": "string", + "pattern": "^(?![.]{1,2}/)[A-Za-z0-9_.-]+/(?![.]{1,2}$)[A-Za-z0-9_.-]+$" + }, "repo": { "enum": [ "developing-today/code",