11698 lines · 398.5 KB · Zig
RawDownload
const std = @import("std");const approval_persistence = @import("approval_persistence.zig");const authority = @import("authority.zig");const auto_classifier_context = @import("../permissions/auto_classifier_context.zig");const communication = @import("communication.zig");const communication_manager_mod = @import("communication_manager.zig");const communication_store = @import("communication_store.zig");const control_store = @import("control_store.zig");const domain = @import("domain.zig");const tool_result = @import("tool_result.zig");const work_events = @import("work_events.zig");const io_mod = @import("../shared/io.zig");const relationship_index = @import("relationship_index.zig");const session = @import("../session/session.zig");const session_child_store = @import("../session/session_child_store.zig");const session_codec = @import("../session/session_codec.zig");const session_store = @import("../session/session_store.zig");const types = @import("../shared/types.zig");const debug_trace = @import("../shared/debug_trace.zig");const text_utils = @import("../shared/text_utils.zig"); const Allocator = std.mem.Allocator;const max_ancestry_depth: usize = 1024;const max_inspected_history_text_bytes: usize = 32 * 1024;const max_inspected_history_field_bytes: usize = 16 * 1024; const BootstrapError = error{    OutOfMemory,    SessionNotFound,    SessionPathUnsafe,    StoreFailure,}; const RelationshipDiscoveryError = error{    OutOfMemory,    RelationshipCycle,    GraphTooDeep,    SessionNotFound,    ControlRecordInvalid,    ControlRecordTooLarge,    ControlPathUnsafe,    StoreFailure,}; pub const FailureCode = enum {    caller_unavailable,    child_unavailable,    control_not_found,    operation_id_required,    invalid_operation_id,    operation_conflict,    operation_replay_expired,    stale_generation,    invalid_state,    relationship_authorization_required,    relationship_cycle,    relationship_already_parented,    relationship_missing_parent,    one_off_not_messageable,    milestone_requires_active_work,    invalid_milestone_caller,    no_active_work,    undeclared_milestone,    control_lock_busy,    control_lock_unsupported,    control_record_invalid,    control_record_too_large,    communication_capacity_exceeded,    control_path_unsafe,    control_commit_indeterminate,    session_not_found,    graph_changed,    graph_too_deep,    invalid_snapshot_query,    generation_exhausted,    store_failure,}; pub const Failure = struct {    code: FailureCode,    retryable: bool = false,}; pub const InspectedHistoryKind = enum {    conversation,    background_command,    interrupted,    compacted_summary,}; pub const InspectedHistoryTurn = struct {    kind: InspectedHistoryKind,    work_id: ?[]u8 = null,    user: ?[]u8 = null,    assistant: ?[]u8 = null,    user_truncated: bool = false,    assistant_truncated: bool = false,     pub fn deinit(self: *InspectedHistoryTurn, alloc: Allocator) void {        if (self.work_id) |value| alloc.free(value);        if (self.user) |value| alloc.free(value);        if (self.assistant) |value| alloc.free(value);        self.* = undefined;    }}; pub const InspectionSourceError = enum {    not_found,    invalid,    unavailable,}; pub const InspectedToolActivity = struct {    sequence: u64,    revision: u64,    timestamp_ms: i64,    work_id: ?[]u8 = null,    tool_name: []u8,    phase: communication.ToolActivityPhase,     pub fn deinit(self: *InspectedToolActivity, alloc: Allocator) void {        if (self.work_id) |value| alloc.free(value);        alloc.free(self.tool_name);        self.* = undefined;    }}; pub const WorkFailure = struct {    work_item_id: []const u8,    reason: []const u8,}; pub fn latestWorkFailure(events: []const domain.Event) ?WorkFailure {    var index = events.len;    while (index > 0) {        index -= 1;        switch (events[index].kind) {            .work_transition => |transition| {                return switch (transition.current) {                    .failed => .{                        .work_item_id = transition.work_item_id,                        .reason = transition.reason orelse continue,                    },                    .completed, .cancelled, .interrupted => null,                    .pending, .running, .awaiting_approval => continue,                };            },            else => {},        }    }    return null;} test "latest work failure is superseded by a later terminal success" {    const events = [_]domain.Event{        .{            .sequence = 1,            .revision = 1,            .id = @constCast("failed"),            .timestamp_ms = 1,            .kind = .{ .work_transition = .{                .work_item_id = @constCast("work-1"),                .previous = .running,                .current = .failed,                .reason = @constCast("read failed"),            } },        },        .{            .sequence = 2,            .revision = 2,            .id = @constCast("completed"),            .timestamp_ms = 2,            .kind = .{ .work_transition = .{                .work_item_id = @constCast("work-2"),                .previous = .running,                .current = .completed,                .reason = null,            } },        },    };    try std.testing.expect(latestWorkFailure(&events) == null);    try std.testing.expectEqualStrings(        "read failed",        latestWorkFailure(events[0..1]).?.reason,    );} pub const Inspection = struct {    child_id: []u8,    generation: u64,    restart_required: bool = false,    status: ?domain.State = null,    configuration: ?domain.Configuration = null,    relationship_selected: bool = false,    parent_id: ?[]u8 = null,    messages: []domain.QueuedMessage,    history: []InspectedHistoryTurn,    history_len: ?usize = null,    history_truncated: bool = false,    history_error: ?InspectionSourceError = null,    events: []domain.Event,    tool_activity_selected: bool = false,    tool_activity: []InspectedToolActivity,    tool_activity_truncated: bool = false,    tool_activity_error: ?InspectionSourceError = null,    failure_work_id: ?[]u8 = null,    failure_reason: ?[]u8 = null,    next_cursor: ?[]u8 = null,     pub fn deinit(self: *Inspection, alloc: Allocator) void {        alloc.free(self.child_id);        if (self.configuration) |*configuration| configuration.deinit(alloc);        if (self.parent_id) |id| alloc.free(id);        for (self.messages) |*message| message.deinit(alloc);        alloc.free(self.messages);        for (self.history) |*turn| turn.deinit(alloc);        alloc.free(self.history);        for (self.events) |*event| event.deinit(alloc);        alloc.free(self.events);        for (self.tool_activity) |*activity| activity.deinit(alloc);        alloc.free(self.tool_activity);        if (self.failure_work_id) |id| alloc.free(id);        if (self.failure_reason) |reason| alloc.free(reason);        if (self.next_cursor) |cursor| alloc.free(cursor);        self.* = undefined;    }}; const HistoryProjection = struct {    turns: []InspectedHistoryTurn,    history_len: ?usize = null,    truncated: bool = false,    source_error: ?InspectionSourceError = null,     fn deinit(self: *HistoryProjection, alloc: Allocator) void {        for (self.turns) |*turn| turn.deinit(alloc);        alloc.free(self.turns);        self.* = undefined;    }}; const ToolActivityProjection = struct {    activity: []InspectedToolActivity,    truncated: bool = false,    source_error: ?InspectionSourceError = null,     fn deinit(self: *ToolActivityProjection, alloc: Allocator) void {        for (self.activity) |*value| value.deinit(alloc);        alloc.free(self.activity);        self.* = undefined;    }}; const FailureProjection = struct {    work_id: ?[]u8 = null,    reason: ?[]u8 = null,}; const HistoryTurnView = struct {    kind: InspectedHistoryKind,    work_id: ?[]const u8 = null,    user: ?[]const u8 = null,    assistant: ?[]const u8 = null,}; pub const TreeRelationshipIssue = enum {    missing_parent,}; pub const TreeDiagnosticCode = enum {    session_unavailable,    control_record_invalid,    control_record_too_large,    control_path_unsafe,    relationship_cycle,    graph_too_deep,    store_failure,}; pub const TreeDiagnostic = struct {    session_id: []u8,    code: TreeDiagnosticCode,     pub fn deinit(self: *TreeDiagnostic, alloc: Allocator) void {        alloc.free(self.session_id);        self.* = undefined;    }}; pub const TreeQuery = struct {    root_id: []const u8,    cursor: ?[]const u8 = null,    anchor_id: ?[]const u8 = null,    limit: usize = domain.default_page_limit,}; pub const TreeNode = struct {    child_id: []u8,    parent_id: []u8,    name: []u8,    mode: domain.Mode,    state: domain.State,    generation: u64,    depth: usize,    relationship_issue: ?TreeRelationshipIssue = null,     pub fn deinit(self: *TreeNode, alloc: Allocator) void {        alloc.free(self.child_id);        alloc.free(self.parent_id);        alloc.free(self.name);        self.* = undefined;    }}; pub const TreeSnapshot = struct {    root_id: []u8,    revision: u64,    restart_required: bool = false,    nodes: []TreeNode,    page_cursor: ?[]u8 = null,    next_cursor: ?[]u8 = null,    diagnostics: []TreeDiagnostic,    diagnostics_truncated: bool = false,     pub fn deinit(self: *TreeSnapshot, alloc: Allocator) void {        alloc.free(self.root_id);        for (self.nodes) |*node| node.deinit(alloc);        alloc.free(self.nodes);        if (self.page_cursor) |cursor| alloc.free(cursor);        if (self.next_cursor) |cursor| alloc.free(cursor);        for (self.diagnostics) |*diagnostic| diagnostic.deinit(alloc);        alloc.free(self.diagnostics);        self.* = undefined;    }}; pub const SnapshotResult = union(enum) {    snapshot: TreeSnapshot,    failure: Failure,     pub fn deinit(self: *SnapshotResult, alloc: Allocator) void {        switch (self.*) {            .snapshot => |*snapshot_value| snapshot_value.deinit(alloc),            .failure => {},        }        self.* = undefined;    }}; pub const Result = union(enum) {    receipt: domain.OperationReceipt,    inspection: Inspection,    failure: Failure,     pub fn deinit(self: *Result, alloc: Allocator) void {        switch (self.*) {            .receipt => |*receipt| receipt.deinit(alloc),            .inspection => |*inspection| inspection.deinit(alloc),            .failure => {},        }        self.* = undefined;    }}; pub const RelationshipAuthorization = union(enum) {    none,    direct,    approval: []const u8,}; const TargetAuthorization = union(enum) {    none,    attached_to_root: []const u8,}; pub const Context = struct {    actor_id: []const u8,    root_user_intent_context: []const u8 = "",    root_user_messages: []const []const u8 = &.{},    root_user_evidence_complete: bool = false,    operation_id: ?[]const u8 = null,    operation_identity_source: ?domain.OperationIdentitySource = null,    operation_identity_epoch: ?u64 = null,    operation_identity_admitted: bool = false,    created_child_id: ?[]const u8 = null,    expected_generation: ?u64 = null,    relationship_authorization: RelationshipAuthorization = .none,    target_authorization: TargetAuthorization = .none,    timestamp_ms: i64,}; pub const Publisher = struct {    context: ?*anyopaque = null,    publish_fn: *const fn (?*anyopaque, control_store.Record) void,     fn publish(self: Publisher, record: control_store.Record) void {        self.publish_fn(self.context, record);    }}; pub const Options = struct {    child_store: session_child_store.Options = .{},    publisher: ?Publisher = null,}; pub const ExecuteError = error{OutOfMemory}; const SnapshotCounters = struct {    discovery_session_ids: usize = 0,    relationship_reads: usize = 0,    control_reads: usize = 0,    candidates_owned: usize = 0,}; const max_snapshot_relationship_reads = relationship_index.max_candidate_reads;const max_snapshot_migration_pages: usize = 4;const max_tree_cursor_bytes: usize = 64 * 1024; const TreeCursorFrame = struct {    generation: u64,    next_offset: u64,}; const ParsedTreeCursor = struct {    frames: []TreeCursorFrame,     fn deinit(self: *ParsedTreeCursor, alloc: Allocator) void {        alloc.free(self.frames);        self.* = undefined;    }}; const TraversalFrame = struct {    parent_id: []u8,    generation: u64,    next_offset: u64,    high_watermark: u64,     fn deinit(self: *TraversalFrame, alloc: Allocator) void {        alloc.free(self.parent_id);        self.* = undefined;    }}; const TreeTraversal = struct {    frames: std.ArrayList(TraversalFrame) = .empty,    root_generation: u64 = 0,    anchored: bool = false,     fn deinit(self: *TreeTraversal, alloc: Allocator) void {        for (self.frames.items) |*frame| frame.deinit(alloc);        self.frames.deinit(alloc);        self.* = undefined;    }}; const TraversalError = error{    OutOfMemory,    InvalidCursor,    StaleCursor,    RelationshipCycle,    GraphTooDeep,    StoreFailure,}; pub const Manager = struct {    sessions: *session_store.Store,    options: Options = .{},     /// Returns an allocator-owned, bounded page of the canonical child tree.    pub fn snapshot(        self: *Manager,        alloc: Allocator,        query: TreeQuery,    ) ExecuteError!SnapshotResult {        return self.snapshotWithCounters(alloc, query, null);    }     fn snapshotWithCounters(        self: *Manager,        alloc: Allocator,        query: TreeQuery,        counters: ?*SnapshotCounters,    ) ExecuteError!SnapshotResult {        return self.snapshotWithDepthLimit(            alloc,            query,            counters,            max_ancestry_depth,        );    }     fn snapshotWithDepthLimit(        self: *Manager,        alloc: Allocator,        query: TreeQuery,        counters: ?*SnapshotCounters,        depth_limit: usize,    ) ExecuteError!SnapshotResult {        std.debug.assert(depth_limit > 0 and depth_limit <= max_ancestry_depth);

Lines 1–500 of 11698.