diff --git a/Rust_RMM_Implementierungsspezifikation.md b/Rust_RMM_Implementierungsspezifikation.md index c0b6b41..dc76908 100644 --- a/Rust_RMM_Implementierungsspezifikation.md +++ b/Rust_RMM_Implementierungsspezifikation.md @@ -1,6 +1,6 @@ # Rust RMM: Architektur und Implementierungsspezifikation -Version 1.30 · 2026-11-16 · Sprache: Deutsch +Version 1.31 · 2026-11-17 · Sprache: Deutsch **Zweck:** Vollständige, eigenständig nutzbare Grundlage für die Implementierung einer mandantenfähigen Plattform zur Inventarisierung, Überwachung und Fernadministration von Kundengeräten durch eine Coding-KI und ein Entwicklungsteam. @@ -67,6 +67,13 @@ darf nur innerhalb derselben ursprünglichen Applyanfrage begrenzt erneut geprüft werden. Keine neue administrative Historienausnahme, Wireänderung, Jobgenehmigung, alte Lease oder Zeitlockerung. +1.30 → 1.31 (2026-11-17): ausdrückliche Userentscheidung „Ja, setze das so +um“: allgemeiner menschlicher WebUI-Abschluss eines `unknown`-Jobs als eigener +Endzustand `closed_unknown`. Die Wirkung bleibt unbekannt; kein Erfolg, +Fehlschlag oder Nichtstart wird behauptet, kein Retry, keine neue Genehmigung. +Der Abschluss hebt ausschließlich die Gerätesperre für neue, einzeln +genehmigte Aufträge auf. Details Kapitel 0.2. + ## Inhaltsverzeichnis - [0 Auftrag und verbindliche Produktanforderungen](#0-auftrag-und-verbindliche-produktanforderungen) @@ -359,6 +366,30 @@ Mandantentrennung und WebUI-Plangenehmigung bleiben verbindlich. Deploymentdaten, offene Konfiguration und reale Nachweise: `docs/server-deployment.md`. Diese Entscheidung ist kein Deploymentnachweis. +### 0.2 Menschlicher Abschluss unbekannter Wirkung (Version 1.31) + +Userentscheidung 2026-11-17. Ein Job im Zustand `unknown` darf ausschließlich +durch einen berechtigten Menschen in der interaktiven WebUI (Recht +`plans:approve`, interaktive Sitzung, CSRF/Origin; im dev/test-Profil sichtbar +simuliert mit `approval_origin`/`testsimulation`) mit Begründung abgeschlossen +werden. MCP, KI, Automatik, API-Token und direkte DB-Aufrufe können das nicht. + +- Der Job erhält den Endzustand `closed_unknown`. Die Wirkung bleibt unbekannt. + Es wird weder Erfolg noch Fehlschlag noch Nichtstart behauptet. +- Originalzustand, Revision und Ergebnis bleiben unveränderlich in + `job_unknown_closures` erhalten; auf den Geräten wird das ursprüngliche + Ergebnis vor dem Ersetzen in `unknown_closure_originals` aufbewahrt. +- Der Versuch wird nie wiederholt; der alte Grant bleibt verbraucht. Ein + abgeschlossener Job ist in der Datenbank gegen jede weitere Zustands-, + Revisions- oder Ergebnisänderung gesperrt. +- Der Server liefert den Abschluss im signierten Abgleich als endgültiges + Ergebnis (`OPERATOR_CLOSED_UNKNOWN`) aus. Agent und Helper akzeptieren genau + diese Form für einen lokal unbekannten Versuch und geben damit nur die + Gerätesperre frei. Neue Aufträge brauchen weiterhin einen eigenen Plan und + eine eigene WebUI-Genehmigung. +- Ein Abschluss ist eine Risikoentscheidung des Menschen und wird mit Person, + Sitzung, Herkunft und Begründung auditiert. + ### 0.1 Auftrag an die implementierende KI **Userentscheidung Version1.21 — signiertes Agent-Selbstupdate parallel:** diff --git a/crates/agent-core/src/helper_reconcile.rs b/crates/agent-core/src/helper_reconcile.rs index 5f0456c..083ca91 100644 --- a/crates/agent-core/src/helper_reconcile.rs +++ b/crates/agent-core/src/helper_reconcile.rs @@ -786,6 +786,14 @@ impl HelperSync { validate_decision(row, local, d)?; if d.unlock { let bytes = unlock_outcome(row, d, current_boot)?; + if d.outcome_state == "closed_unknown" { + crate::ledger::retain_closure_original( + &tx, + row.grant_id, + &row.outcome_bytes, + &bytes, + )?; + } let preserve = crate::windows_system_nonstart::preserve_original_unlock( &tx, &self.binding, @@ -1523,6 +1531,7 @@ fn load_rows( | "failed" | "cancelled" | "expired" + | "closed_unknown" | "running" ), "UNKNOWN_LOCAL_STATE" @@ -1610,7 +1619,7 @@ fn load_rows( fn definitive(row: &LocalAttempt) -> bool { matches!( row.state.as_str(), - "succeeded" | "failed" | "cancelled" | "expired" + "succeeded" | "failed" | "cancelled" | "expired" | "closed_unknown" ) && !row.outcome_bytes.is_empty() } fn validate_summary(row: &LocalAttempt, a: &AttemptView) -> Result<()> { @@ -1670,7 +1679,7 @@ fn validate_decision(row: &LocalAttempt, a: &AttemptView, d: &AttemptDecision) - !d.unlock || matches!( d.outcome_state.as_str(), - "succeeded" | "failed" | "cancelled" | "expired" + "succeeded" | "failed" | "cancelled" | "expired" | "closed_unknown" ), "UNKNOWN_CANNOT_UNLOCK" ); @@ -1689,6 +1698,11 @@ fn unlock_outcome(row: &LocalAttempt, d: &AttemptDecision, current_boot: Uuid) - && o.state == d.outcome_state, "ROOT_CANONICAL_UNLOCK_OUTCOME" ); + if bytes != row.outcome_bytes + && crate::reconcile::operator_closure(&d.reason, &row.state, &o) + { + return Ok(bytes); + } if bytes != row.outcome_bytes { ensure!( row.action == "reboot" diff --git a/crates/agent-core/src/ledger.rs b/crates/agent-core/src/ledger.rs index a0a9f75..13b2545 100644 --- a/crates/agent-core/src/ledger.rs +++ b/crates/agent-core/src/ledger.rs @@ -34,6 +34,37 @@ pub fn initialize_ledger(db: &rusqlite::Connection) -> Result<()> { Ok(()) } +/// Before a human WebUI closure replaces the unresolved local outcome, keep the +/// exact original outcome bytes once. A differing second copy fails closed. +pub(crate) fn retain_closure_original( + db: &rusqlite::Connection, + grant: Uuid, + original: &[u8], + closure: &[u8], +) -> Result<()> { + db.execute_batch("CREATE TABLE IF NOT EXISTS unknown_closure_originals(grant_id TEXT PRIMARY KEY, original_outcome BLOB NOT NULL, closure_outcome BLOB NOT NULL);")?; + let existing: Option<(Vec, Vec)> = db + .query_row( + "SELECT original_outcome,closure_outcome FROM unknown_closure_originals WHERE grant_id=?1", + [grant.to_string()], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional()?; + match existing { + Some((old, done)) => ensure!( + done == closure && (old == original || original == closure), + "CLOSURE_ORIGINAL_CHANGED" + ), + None => { + db.execute( + "INSERT INTO unknown_closure_originals VALUES(?1,?2,?3)", + params![grant.to_string(), original, closure], + )?; + } + } + Ok(()) +} + /// Legacy split reservation API retained for old fixtures/readers. Production /// callers use begin_execution so a crash cannot lose the original start witness. pub fn consume(db: &mut rusqlite::Connection, p: &ExecutionPermitPayload) -> Result<()> { diff --git a/crates/agent-core/src/reconcile.rs b/crates/agent-core/src/reconcile.rs index 7754354..285583d 100644 --- a/crates/agent-core/src/reconcile.rs +++ b/crates/agent-core/src/reconcile.rs @@ -1036,6 +1036,7 @@ impl ClientSync { let previous = resolved .or(previous) .context("LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISSING")?; + let original = previous.clone(); let prior = canonical_outcome_bytes(&serde_json::from_slice::( &previous, )?)?; @@ -1062,6 +1063,9 @@ impl ClientSync { grant, &bytes, )?; + if outcome.state == "closed_unknown" { + crate::ledger::retain_closure_original(&tx, grant, &original, &bytes)?; + } tx.execute( "UPDATE consumed SET result=?2 WHERE grant_id=?1", params![grant.to_string(), bytes], @@ -1200,7 +1204,29 @@ pub(crate) fn outcome(r: &JobResult) -> Result { }) } fn terminal(state: &str) -> bool { - matches!(state, "succeeded" | "failed" | "cancelled" | "expired") + matches!( + state, + "succeeded" | "failed" | "cancelled" | "expired" | "closed_unknown" + ) +} +/// Server-signed final bytes of a human WebUI closure for an attempt whose +/// effect stayed unknown. They never claim success, failure or nonstart. +pub(crate) fn operator_closure( + reason: &str, + local_state: &str, + outcome: &ReconciledOutcome, +) -> bool { + reason == "OPERATOR_CLOSED_UNKNOWN" + && local_state == "unknown" + && outcome.state == "closed_unknown" + && outcome.error_code == "OPERATOR_CLOSED_UNKNOWN" + && outcome.exit_code.is_none() + && outcome.stdout.is_empty() + && outcome.stderr.is_empty() + && outcome.evidence["postconditions_passed"] == false + && outcome.evidence["effect"] == "unknown" + && outcome.evidence["closed_by_human"] == true + && outcome.evidence["retry"] == false } fn optional_uuid(s: &str) -> Result> { if s.is_empty() { @@ -1861,7 +1887,7 @@ fn validate_attempt( && o.state == d.outcome_state, "SYNC_CANONICAL_OUTCOME" ); - if bytes != local.outcome_bytes { + if bytes != local.outcome_bytes && !operator_closure(&d.reason, &local.state, &o) { ensure!( matches!(job.action, rmm_domain::jobs::Action::Reboot { .. }) && d.outcome_state == "succeeded" @@ -2166,3 +2192,39 @@ pub fn closed_control_contract(raw: &[u8]) -> Result { json!({"actual_closed_partial_edge_accepted":true,"mutated_agent_request_rejected":true,"mutated_server_signature_and_ack_rejected":true,"admission_read_only":true,"hidden_open_grant_rejected":true,"explicit_idle_attestation_required":true,"typed_precommit_clock_keeps_capture_without_writes":true,"fresh_request_keeps_both_heads":true,"old_authority_reused":false,"new_ready_or_unlock":false,"product_databases_opened":false,"effects":false}), ) } + +#[cfg(test)] +mod closure_tests { + use super::*; + + #[test] + fn only_a_human_closure_of_a_locally_unknown_attempt_is_accepted() { + let closed = ReconciledOutcome { + state: "closed_unknown".into(), + stdout: vec![], + stderr: vec![], + exit_code: None, + output_truncated: false, + reboot_required: false, + evidence: serde_json::json!({"postconditions_passed":false,"effect":"unknown","closed_by_human":true,"retry":false}), + error_code: "OPERATOR_CLOSED_UNKNOWN".into(), + }; + assert!(operator_closure("OPERATOR_CLOSED_UNKNOWN", "unknown", &closed)); + assert!(!operator_closure("DEFINITIVE_OUTCOME_RECONCILED", "unknown", &closed)); + assert!(!operator_closure("OPERATOR_CLOSED_UNKNOWN", "running", &closed)); + assert!(!operator_closure("OPERATOR_CLOSED_UNKNOWN", "succeeded", &closed)); + for case in 0..6 { + let mut other = closed.clone(); + match case { + 0 => other.state = "failed".into(), + 1 => other.error_code = "SCRIPT_FAILED".into(), + 2 => other.exit_code = Some(0), + 3 => other.stdout = b"x".to_vec(), + 4 => other.evidence["postconditions_passed"] = true.into(), + _ => other.evidence["retry"] = true.into(), + } + assert!(!operator_closure("OPERATOR_CLOSED_UNKNOWN", "unknown", &other)); + } + assert!(terminal("closed_unknown")); + } +} diff --git a/crates/agent-windows/src/job_readiness.rs b/crates/agent-windows/src/job_readiness.rs index 2c118e2..839e57f 100644 --- a/crates/agent-windows/src/job_readiness.rs +++ b/crates/agent-windows/src/job_readiness.rs @@ -62,18 +62,22 @@ pub fn clock_code(error: &anyhow::Error) -> &'static str { /// Refresh is control work, not permission. A temporary loss of the100ms clock /// evidence never discards an otherwise retained signed decision or extends it. /// Fresh clock/readiness checks remain mandatory at each actual job gate. +/// A requested refresh waits at least `MIN_SYNC_INTERVAL` after the previous +/// start, so a persistently not-ready decision cannot become a tight loop. +pub const MIN_SYNC_INTERVAL: std::time::Duration = std::time::Duration::from_secs(3); pub fn refresh_due( needs_sync: bool, elapsed: std::time::Duration, valid_until: Option>, clock_upper: Option>, ) -> bool { - needs_sync - || elapsed >= std::time::Duration::from_secs(40) - || valid_until.is_none() - || valid_until - .zip(clock_upper) - .is_some_and(|(until, upper)| upper >= until) + elapsed >= MIN_SYNC_INTERVAL + && (needs_sync + || elapsed >= std::time::Duration::from_secs(40) + || valid_until.is_none() + || valid_until + .zip(clock_upper) + .is_some_and(|(until, upper)| upper >= until)) } #[cfg(windows)] pub fn persist(state: &Path, value: &Observation) -> Result<()> { @@ -143,11 +147,14 @@ mod tests { let now = chrono::DateTime::from_timestamp(100, 0).unwrap(); let until = now + chrono::Duration::seconds(30); let one = std::time::Duration::from_secs(1); - assert!(!refresh_due(false, one, Some(until), None)); - assert!(!refresh_due(false, one, Some(until), Some(now))); - assert!(refresh_due(false, one, Some(until), Some(until))); - assert!(refresh_due(false, one, None, None)); - assert!(refresh_due(true, one, Some(until), None)); + let min = MIN_SYNC_INTERVAL; + assert!(!refresh_due(false, min, Some(until), None)); + assert!(!refresh_due(false, min, Some(until), Some(now))); + assert!(refresh_due(false, min, Some(until), Some(until))); + assert!(refresh_due(false, min, None, None)); + assert!(refresh_due(true, min, Some(until), None)); + // No trigger may restart Sync sooner than the minimum interval. + assert!(!refresh_due(true, one, None, Some(until))); assert!(refresh_due( false, std::time::Duration::from_secs(40), diff --git a/crates/domain/src/jobs.rs b/crates/domain/src/jobs.rs index d4bc6de..1156de3 100644 --- a/crates/domain/src/jobs.rs +++ b/crates/domain/src/jobs.rs @@ -738,12 +738,15 @@ pub enum JobState { Cancelled, Expired, Unknown, + /// A human closed an unknown attempt in the WebUI. The effect stays + /// unknown; the attempt is final and is never retried or reinterpreted. + ClosedUnknown, } impl JobState { pub fn terminal(self) -> bool { matches!( self, - Self::Succeeded | Self::Failed | Self::Cancelled | Self::Expired + Self::Succeeded | Self::Failed | Self::Cancelled | Self::Expired | Self::ClosedUnknown ) } pub fn allows(self, next: Self) -> bool { diff --git a/crates/server/src/jobs.rs b/crates/server/src/jobs.rs index 5b3f4f8..522c6fc 100644 --- a/crates/server/src/jobs.rs +++ b/crates/server/src/jobs.rs @@ -84,6 +84,10 @@ pub fn routes(r: Router) -> Router { "/api/v1/tenants/{tenant}/jobs/{job}/cancel", post(cancel_http), ) + .route( + "/api/v1/tenants/{tenant}/jobs/{job}/unknown-closure", + post(close_unknown_http), + ) } #[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)] #[serde(deny_unknown_fields)] @@ -1081,7 +1085,13 @@ pub async fn operation( "needs_attention" } else if c("succeeded") == n { "succeeded" - } else if c("succeeded") + c("failed") + c("cancelled") + c("expired") == n { + } else if c("succeeded") + + c("failed") + + c("cancelled") + + c("expired") + + c("closed_unknown") + == n + { if c("succeeded") > 0 { "partially_succeeded" } else if c("cancelled") == n { @@ -1204,6 +1214,95 @@ async fn job_http( let p = principal(&s, &h, false).await?; Ok(Json(job(&s, &p, t, id).await?)) } +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CloseUnknown { + pub attempt_id: Uuid, + pub revision: i64, + pub reason: String, +} +/// Human WebUI only: accept an unknown attempt as unresolved and final. The +/// effect stays unknown; there is no retry, new grant or reinterpretation. +pub async fn close_unknown( + state: &crate::State, + p: &Principal, + tenant: Uuid, + id: Uuid, + input: CloseUnknown, +) -> Result { + scope(p, tenant, true)?; + let session = p + .session_hash + .clone() + .ok_or(Error(StatusCode::FORBIDDEN, "INTERACTIVE_AUTH_REQUIRED"))?; + if input.reason.trim().is_empty() || input.reason.len() > 1024 { + return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR")); + } + let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?; + crate::permissions::require_principal(&mut tx, p, "plans:approve").await?; + let row = sqlx::query( + "SELECT attempt_id,state,revision,result FROM jobs WHERE job_id=$1 FOR UPDATE", + ) + .bind(id) + .fetch_optional(&mut *tx) + .await? + .ok_or_else(missing)?; + if row.get::("attempt_id") != input.attempt_id + || row.get::("revision") != input.revision + { + return Err(fail("JOB_CHANGED")); + } + if row.get::("state") != "unknown" { + return Err(fail("JOB_NOT_UNKNOWN")); + } + let original: Option = row.get("result"); + let grant: Option = sqlx::query_scalar( + "SELECT grant_id FROM execution_permits WHERE job_id=$1 AND attempt_id=$2", + ) + .bind(id) + .bind(input.attempt_id) + .fetch_optional(&mut *tx) + .await?; + let closure = Uuid::new_v4(); + sqlx::query("INSERT INTO job_unknown_closures(tenant_id,closure_id,job_id,attempt_id,grant_id,original_state,original_revision,original_result,principal,session_hash,approval_origin,testsimulation,reason) VALUES($1,$2,$3,$4,$5,'unknown',$6,$7,$8,$9,$10,$11,$12)") + .bind(tenant).bind(closure).bind(id).bind(input.attempt_id).bind(grant) + .bind(input.revision).bind(&original).bind(&p.name).bind(&session) + .bind(p.approval_origin()).bind(p.testsimulation).bind(&input.reason) + .execute(&mut *tx).await?; + let original_sha256 = original + .as_ref() + .map(|v| rmm_domain::jobs::hash(&serde_json::to_vec(v).unwrap_or_default())); + let result = json!({"stdout":[],"stderr":[],"exit_code":null,"output_truncated":false,"reboot_required":false, + "error_code":"OPERATOR_CLOSED_UNKNOWN","grant_id":grant.map(|g|g.to_string()).unwrap_or_default(), + "evidence":{"postconditions_passed":false,"effect":"unknown","closed_by_human":true,"closure_id":closure, + "original_state":"unknown","original_revision":input.revision,"original_result_sha256":original_sha256, + "retry":false,"approval_origin":p.approval_origin(),"testsimulation":p.testsimulation}}); + sqlx::query("UPDATE jobs SET state='closed_unknown',revision=revision+1,result=$2,pending_reason=NULL WHERE job_id=$1 AND state='unknown'") + .bind(id) + .bind(&result) + .execute(&mut *tx) + .await?; + sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,'job_unknown_closed',$4,now())") + .bind(tenant) + .bind(Uuid::new_v4()) + .bind(&p.name) + .bind(json!({"job_id":id,"attempt_id":input.attempt_id,"grant_id":grant,"closure_id":closure, + "original_revision":input.revision,"reason":input.reason,"session_hash":session, + "approval_origin":p.approval_origin(),"testsimulation":p.testsimulation})) + .execute(&mut *tx) + .await?; + tx.commit().await?; + job(state, p, tenant, id).await +} +async fn close_unknown_http( + State(s): State, + h: HeaderMap, + Path((t, id)): Path<(Uuid, Uuid)>, + Json(i): Json, +) -> Result> { + let p = principal(&s, &h, true).await?; + Ok(Json(close_unknown(&s, &p, t, id, i).await?)) +} async fn cancel_http( State(s): State, h: HeaderMap, diff --git a/crates/server/src/synchronization.rs b/crates/server/src/synchronization.rs index 707e253..0a378ce 100644 --- a/crates/server/src/synchronization.rs +++ b/crates/server/src/synchronization.rs @@ -44,7 +44,10 @@ fn outcome(state: &str, value: &Value) -> Result { }) } fn unsettled(state: &str) -> bool { - !matches!(state, "succeeded" | "failed" | "cancelled" | "expired") + !matches!( + state, + "succeeded" | "failed" | "cancelled" | "expired" | "closed_unknown" + ) } fn clean_unstarted(local: &SyncAttempt, reserved: bool) -> bool { !reserved @@ -420,6 +423,7 @@ pub async fn reconcile( | "verifying" | "awaiting_reboot" | "unknown" + | "closed_unknown" | "succeeded" | "failed" | "cancelled" @@ -444,7 +448,7 @@ pub async fn reconcile( ensure!(parsed.state == local.state, "local outcome state mismatch"); } } - let rows=sqlx::query("SELECT j.job_id,j.attempt_id,j.payload_hash,j.payload,j.state,j.revision,j.result,j.start_reserved,b.acknowledged_at FROM jobs j LEFT JOIN outbox b ON b.tenant_id=j.tenant_id AND b.job_id=j.job_id WHERE j.agent_id=$1 AND (j.state NOT IN ('succeeded','failed','cancelled','expired') OR j.job_id=ANY($2)) ORDER BY j.job_id LIMIT 257 FOR UPDATE OF j").bind(agent).bind(locals.keys().copied().collect::>()).fetch_all(&mut **tx).await?; + let rows=sqlx::query("SELECT j.job_id,j.attempt_id,j.payload_hash,j.payload,j.state,j.revision,j.result,j.start_reserved,b.acknowledged_at FROM jobs j LEFT JOIN outbox b ON b.tenant_id=j.tenant_id AND b.job_id=j.job_id WHERE j.agent_id=$1 AND (j.state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown') OR j.job_id=ANY($2)) ORDER BY j.job_id LIMIT 257 FOR UPDATE OF j").bind(agent).bind(locals.keys().copied().collect::>()).fetch_all(&mut **tx).await?; if rows.len() > 256 { reason = "SYNC_SERVER_JOB_LIMIT".into(); chain_valid = false; @@ -743,7 +747,9 @@ pub async fn reconcile( && result.grant_id == local.grant_id, "sync result binding" ); - if !manual { + // A human-closed attempt is final; late agent evidence is neither + // replayed into nor allowed to reinterpret the closed ledger row. + if !manual && server_state != "closed_unknown" { let evidence = local .result_envelope .as_ref() @@ -857,13 +863,22 @@ pub async fn reconcile( if let Some(value) = final_row.get::, _>("result") { let bytes = canonical_outcome_bytes(&outcome(&terminal, &value)?)?; let hash = hash(&bytes); - if prior_hash.as_deref() == Some(&hash) || reboot_reconciled { - decision.outcome_sha256 = Some(hash); + // Human WebUI closure: only an attempt still locally unknown (or + // already closed) receives the server-derived final bytes. + let closed = terminal == "closed_unknown" + && matches!(local.state.as_str(), "unknown" | "closed_unknown"); + if prior_hash.as_deref() == Some(&hash) || reboot_reconciled || closed { decision.unlock = local.consumption == "consumed" && grant_matches; - if reboot_reconciled { + if reboot_reconciled || (closed && prior_hash.as_deref() != Some(&hash)) { decision.outcome_bytes = bytes; } - decision.reason = "DEFINITIVE_OUTCOME_RECONCILED".into(); + decision.outcome_sha256 = Some(hash); + decision.reason = if closed { + "OPERATOR_CLOSED_UNKNOWN" + } else { + "DEFINITIVE_OUTCOME_RECONCILED" + } + .into(); } else { ready = false; decision.reason = "LOCAL_OUTCOME_MISMATCH".into(); @@ -968,7 +983,7 @@ pub async fn reconcile( }) } async fn mark_unknown(tx: &mut Transaction<'_, Postgres>, job: Uuid, reason: &str) -> Result<()> { - sqlx::query("UPDATE jobs SET state='unknown',start_reserved=true,pending_reason='reconciliation_required',result=COALESCE(result,'{}'::jsonb)||jsonb_build_object('error_code',$2::text,'source_id','authoritative_sync') WHERE job_id=$1 AND state NOT IN ('succeeded','failed','cancelled','expired')").bind(job).bind(reason).execute(&mut **tx).await?; + sqlx::query("UPDATE jobs SET state='unknown',start_reserved=true,pending_reason='reconciliation_required',result=COALESCE(result,'{}'::jsonb)||jsonb_build_object('error_code',$2::text,'source_id','authoritative_sync') WHERE job_id=$1 AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')").bind(job).bind(reason).execute(&mut **tx).await?; Ok(()) } #[cfg(test)] diff --git a/docs/project-decisions.md b/docs/project-decisions.md index 74ae81f..82c92b9 100644 --- a/docs/project-decisions.md +++ b/docs/project-decisions.md @@ -1,6 +1,15 @@ # Verbindliche Projektentscheidungen -Stand: **2026-11-16**, Spezifikation **1.30** (`Rust_RMM_Implementierungsspezifikation.md`). Die ausdrücklichen normativen Entscheidungen in Kapitel 0 haben Vorrang vor früheren Architekturannahmen. Version 1.6 ersetzt die lokale Servertopologie durch den dedizierten Internetserver; Version 1.7 präzisiert das Notebook als reinen Entwicklungsrechner; Version 1.8 erlaubt vorgezogene parallele Windows-Entwicklung. +Stand: **2026-11-17**, Spezifikation **1.31** (`Rust_RMM_Implementierungsspezifikation.md`). Die ausdrücklichen normativen Entscheidungen in Kapitel 0 haben Vorrang vor früheren Architekturannahmen. Version 1.6 ersetzt die lokale Servertopologie durch den dedizierten Internetserver; Version 1.7 präzisiert das Notebook als reinen Entwicklungsrechner; Version 1.8 erlaubt vorgezogene parallele Windows-Entwicklung. + +## Menschlicher Abschluss von unknown-Jobs (Version 1.31) + +Userentscheidung 17. November 2026 („Ja, setze das so um“): Statt weiterer +Einzelausnahmen (221, 357) gibt es einen allgemeinen menschlichen +WebUI-Abschluss eines `unknown`-Jobs als Endzustand `closed_unknown`. Die +Wirkung bleibt unbekannt, kein Retry, keine neue Genehmigung; nur die +Gerätesperre wird aufgehoben. Nicht über MCP/KI/Automatik. Originale bleiben +erhalten. Erster Anwendungsfall ist Job `7d756c34…`. Details Spezifikation 0.2. **Technische S2-Korrektur, keine neue Userausnahme:** Der normale frische Onlineabgleich kann eine genau bewiesene, bereits wirkungslos geschlossene diff --git a/migrations/0022_job_unknown_closure.sql b/migrations/0022_job_unknown_closure.sql new file mode 100644 index 0000000..71db974 --- /dev/null +++ b/migrations/0022_job_unknown_closure.sql @@ -0,0 +1,51 @@ +-- Human WebUI closure of an unknown job attempt (user decision 2026-11-17). +-- The effect remains unknown. The attempt becomes final, is never retried and +-- is never reinterpreted as success, failure or nonstart. The original state, +-- revision and result are retained immutably in the closure row. +ALTER TABLE jobs DROP CONSTRAINT jobs_state_check; +ALTER TABLE jobs ADD CONSTRAINT jobs_state_check CHECK(state IN ('queued','accepted','running','verifying','awaiting_reboot','succeeded','failed','cancelled','expired','unknown','closed_unknown')); +CREATE TABLE job_unknown_closures ( + tenant_id uuid NOT NULL, + closure_id uuid PRIMARY KEY, + job_id uuid NOT NULL, + attempt_id uuid NOT NULL, + grant_id uuid, + original_state text NOT NULL CHECK(original_state='unknown'), + original_revision bigint NOT NULL CHECK(original_revision>=0), + original_result jsonb, + principal text NOT NULL CHECK(length(principal) BETWEEN 1 AND 256), + session_hash text NOT NULL CHECK(session_hash ~ '^[0-9a-f]{64}$'), + approval_origin text NOT NULL, + testsimulation boolean NOT NULL, + reason text NOT NULL CHECK(length(reason) BETWEEN 1 AND 1024), + created_at timestamptz NOT NULL DEFAULT now(), + UNIQUE(tenant_id,job_id), + FOREIGN KEY(tenant_id,job_id,attempt_id) REFERENCES jobs(tenant_id,job_id,attempt_id), + CHECK((approval_origin='dev_test_browser_simulation' AND testsimulation) OR (approval_origin='human_webui' AND NOT testsimulation)) +); +ALTER TABLE job_unknown_closures ENABLE ROW LEVEL SECURITY; +ALTER TABLE job_unknown_closures FORCE ROW LEVEL SECURITY; +CREATE POLICY tenant_scope ON job_unknown_closures USING(tenant_id::text=current_setting('app.tenant_id',true)) WITH CHECK(tenant_id::text=current_setting('app.tenant_id',true)); +GRANT SELECT,INSERT ON job_unknown_closures TO rmm_app; +CREATE TRIGGER immutable_content BEFORE UPDATE OR DELETE ON job_unknown_closures FOR EACH ROW EXECUTE FUNCTION immutable_plan(); +-- A job enters closed_unknown only from unknown with a matching closure row, +-- and a closed job never changes state, revision or result again. +CREATE FUNCTION guard_closed_unknown() RETURNS trigger LANGUAGE plpgsql +SET search_path=pg_catalog,public AS $$ +DECLARE c job_unknown_closures%ROWTYPE; +BEGIN + IF OLD.state='closed_unknown' THEN + IF NEW.state IS DISTINCT FROM OLD.state OR NEW.revision IS DISTINCT FROM OLD.revision OR NEW.result IS DISTINCT FROM OLD.result THEN + RAISE EXCEPTION 'JOB_CLOSED_UNKNOWN_IMMUTABLE'; + END IF; + ELSIF NEW.state='closed_unknown' THEN + SELECT * INTO c FROM job_unknown_closures WHERE tenant_id=NEW.tenant_id AND job_id=NEW.job_id; + IF NOT FOUND OR OLD.state IS DISTINCT FROM 'unknown' OR c.attempt_id IS DISTINCT FROM NEW.attempt_id + OR c.original_revision IS DISTINCT FROM OLD.revision OR c.original_result IS DISTINCT FROM OLD.result + OR NEW.revision IS DISTINCT FROM OLD.revision+1 THEN + RAISE EXCEPTION 'JOB_CLOSED_UNKNOWN_REQUIRES_CLOSURE'; + END IF; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER guard_closed_unknown BEFORE UPDATE ON jobs FOR EACH ROW EXECUTE FUNCTION guard_closed_unknown(); diff --git a/web/src/main.tsx b/web/src/main.tsx index a81d2dc..2cc713c 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -245,8 +245,20 @@ function OperationDetail({ tenantId, id, auth, openPlan }: { tenantId: string; i function JobDetail({ tenantId, id, auth }: { tenantId: string; id: string; auth: Session }) { const job = useResource(async signal => record(await request(tenantPath(tenantId, `/jobs/${encodeURIComponent(id)}`), { signal })), [tenantId, id], true); const [error, setError] = useState(null), [busy, setBusy] = useState(false); - return

Job {id}

verifying = Nachprüfung läuft · unknown = Wirkung unklar, kein Retry · awaiting_reboot = Neustart oder Wiederanmeldung zur Nachprüfung ausstehend. Neue Neustartjobs benötigen eine eigene Genehmigung. cancel_requested ist kein bestätigter Abbruch, keine Rollbackzusage.

{job.data && <>} -
{ e.preventDefault(); const reason = new FormData(e.currentTarget).get('reason'); setBusy(true); setError(null); try { await request(tenantPath(tenantId, `/jobs/${encodeURIComponent(id)}/cancel`), { csrf: auth.csrf_token, body: { reason } }); job.reload(); } catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>
; + return

Job {id}

verifying = Nachprüfung läuft · unknown = Wirkung unklar, kein Retry · closed_unknown = von einem Menschen abgeschlossen, Wirkung weiterhin unbekannt, kein Retry · awaiting_reboot = Neustart oder Wiederanmeldung zur Nachprüfung ausstehend. Neue Neustartjobs benötigen eine eigene Genehmigung. cancel_requested ist kein bestätigter Abbruch, keine Rollbackzusage.

{job.data && <>} +
{ e.preventDefault(); const reason = new FormData(e.currentTarget).get('reason'); setBusy(true); setError(null); try { await request(tenantPath(tenantId, `/jobs/${encodeURIComponent(id)}/cancel`), { csrf: auth.csrf_token, body: { reason } }); job.reload(); } catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>
+ {job.data && stringField(job.data, 'state') === 'unknown' && }
; +} +function UnknownClosure({ tenantId, id, job, auth, done }: { tenantId: string; id: string; job: RecordValue; auth: Session; done: () => void }) { + const [confirmed, setConfirmed] = useState(false), [reason, setReason] = useState(''), [busy, setBusy] = useState(false), [error, setError] = useState(null); + const eligible = allowed(auth, 'plans:approve') && !!auth.csrf_token; + return

Unknown-Job abschließen

+

Die Wirkung dieses Versuchs bleibt unbekannt. Der Abschluss wertet ihn weder als Erfolg noch als Fehlschlag oder Nichtstart, wiederholt ihn nie und erteilt keine neue Genehmigung. Er hebt nur die Sperre des Geräts für neue, eigens genehmigte Aufträge auf. Originaldaten bleiben erhalten.

+ + +
; } function Workspace({ auth, logout }: { auth: Session; logout: () => void }) { const tenants = useResource(async signal => page(await request('/api/v1/tenants', { signal })), []);