{"modulePath":"github.com/memcode-ai/memcode","version":"v0.56.16","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package autonomy\n\nPackage personal implements the domain-general durable state and runtime primitives for autonomous agents.\n\n## Constants\n\n```go\nconst (\n\tBrowserExistingChrome = \"existing_chrome\"\n\tBrowserEphemeral      = \"ephemeral\"\n)\n```\n\n## Functions\n\n```go\nfunc AppendMemory(home, note string) error\n```\nAppendMemory adds one durable note. Append-only and deduplicated: a wake that re-learns something it already recorded must not grow the file without bound, since every line is replayed into the model on every future wake.\n\n```go\nfunc CanonicalFilesystemGrant(path string) (string, error)\n```\n\n```go\nfunc CanonicalPolicy(p DelegationPolicy) ([]byte, string, error)\n```\n\n```go\nfunc CommitGenerated(root, message string) error\n```\n\n```go\nfunc InitializeGeneratedWorkspace(home string) (string, error)\n```\n\n```go\nfunc InitializeHome(home string) error\n```\n\n```go\nfunc IsRestriction(parent, next DelegationPolicy) bool\n```\n\n```go\nfunc NextDue(kind, spec string, after time.Time) (time.Time, error)\n```\nNextDue resolves when a trigger should next fire.\n\nThe only kinds here are the ones an AGENT writes for itself from inside a run (schedule\\_wake: \"come back in 45 minutes\"), which are always a single future instant. Recurring cadence a HUMAN configures is not a trigger at all — it is an ordinary gateway schedule delivering to agent:\\\u003cname\u003e, parsed and validated once by gwconfig (see ValidateScheduleSpec/BuildSchedule).\n\nThat split is deliberate: this package used to carry its own interval/cron parsing, which meant two cron implementations in one binary and two places for scheduling rules to disagree. Adding kinds back here would rebuild the second scheduler — internal/guard's TestSingleCronParser fails if it happens.\n\n```go\nfunc PathWithinGrant(path, root string) bool\n```\nPathWithinGrant reports whether path resolves (symlinks evaluated) to a location inside the canonical grant root. The requested path's symlinks are resolved before the containment check so a symlink inside a granted dir that points outside cannot escape the boundary.\n\n```go\nfunc PrepareRunDirectory(home, runID string, e ExecutionEnvelope) (string, error)\n```\n\n```go\nfunc ReadMemory(home string) string\n```\nReadMemory returns the agent's memory, or \"\" when it has none yet.\n\n```go\nfunc RedactActionRequest(v json.RawMessage) json.RawMessage\n```\n\n```go\nfunc RollbackGenerated(root, revision string) error\n```\n\n```go\nfunc SandboxAvailable() bool\n```\n\n```go\nfunc ValidateDelegation(parent DelegationPolicy, e ExecutionEnvelope) error\n```\n\n```go\nfunc ValidateExecutiveBudget(maxSeconds, maxTools, maxDelegation int) error\n```\n\n```go\nfunc WriteConfigMirror(ctx context.Context, home string, s *Store) error\n```\nWriteConfigMirror regenerates config.yaml — ONE readable file in the agent's home holding the authority state that lives in the database: its policies (draft and approved) and its resource grants. This is what makes \\`ls ~/.memcode/agents/\\\u003cname\u003e/\\` show something a person can read, diff, and grep instead of only an opaque SQLite file, matching every other piece of memcode config (gateway.yaml, .mcp.json, MEMCODE.md, skills).\n\nThe agent's objective, autonomy, browser mode, and pause state are NOT here: they are ordinary configuration in gateway.yaml, which is already a readable file. Mirroring them too would mean two places to look and two chances to disagree.\n\nThis file is a MIRROR, not the source of truth — the DB stays authoritative for two reasons that are correctness, not habit:\n\n  - Policy approval is a deliberate hash-gated ceremony (see ApprovePolicy): a autonomous agent runs unsupervised, so \"the document a human actually reviewed\" must be pinned by hash, not re-derived from whatever the file happens to say at wake time. Editing config.yaml's policy section and having it silently take effect would defeat that.\n  - The action/trigger/interaction journal needs atomic claim/complete semantics under concurrent access (the gateway wake loop and an admin session can both touch the same agent) — a SQL transaction gives that almost for free; a flat file would need to reinvent it (see the atomicfile-write fix elsewhere in this package for how easily a plain file write loses that property). So the run journal stays out of this file entirely — read it with gw\\_journal.\n\nCalled after every mutation to policies/resources (gw\\_policy, gw\\_grant), best-effort: a mirror failure never blocks the underlying write, which has already succeeded.\n\n## Types\n\n```go\ntype Action struct {\n\tID, ObjectiveID, SubgoalID, RunID, Kind, Target, ConsequenceClass, PolicyHash, Status, IdempotencyKey string\n\t// JobID links a delegate action to the detached job it spawned, so a later\n\t// wake can find the action to close out (see Store.ActionForJob).\n\tJobID                     string\n\tRequest, Result, Evidence json.RawMessage\n\tCreatedAt, UpdatedAt      time.Time\n}\n```\n\n```go\ntype ActionIntent struct {\n\tID, ObjectiveID, SubgoalID, RunID, Kind, Target string\n\tConsequence                                     ConsequenceClass\n\tPolicyHash                                      string\n\tRequest                                         json.RawMessage\n\tIdempotencyKey                                  string\n}\n```\n\n```go\ntype ActionStatus string\n```\n\n```go\nconst (\n\tActionPlanned   ActionStatus = \"planned\"\n\tActionReserved  ActionStatus = \"reserved\"\n\tActionRunning   ActionStatus = \"running\"\n\tActionSucceeded ActionStatus = \"succeeded\"\n\tActionFailed    ActionStatus = \"failed\"\n\tActionUncertain ActionStatus = \"uncertain\"\n\tActionCancelled ActionStatus = \"cancelled\"\n)\n```\n\n```go\ntype ConsequenceClass string\n```\n\n```go\nconst (\n\tObserve                ConsequenceClass = \"observe\"\n\tLocalMutation          ConsequenceClass = \"local_mutation\"\n\tExternalEffect         ConsequenceClass = \"external_effect\"\n\tExternalRepresentation ConsequenceClass = \"external_representation\"\n\tFinancial              ConsequenceClass = \"financial\"\n\tLegalAttestation       ConsequenceClass = \"legal_attestation\"\n\tDestructive            ConsequenceClass = \"destructive\"\n)\n```\n\n```go\ntype DelegationPolicy struct {\n\tObjectiveScope      string             `json:\"objective_scope\"`\n\tAllowedTools        []string           `json:\"allowed_tools,omitempty\"`\n\tFilesystemRoots     map[string]string  `json:\"filesystem_roots,omitempty\"`\n\tBrowserOrigins      []string           `json:\"browser_origins,omitempty\"`\n\tMCPTools            []string           `json:\"mcp_tools,omitempty\"`\n\tConsequenceClasses  []ConsequenceClass `json:\"consequence_classes,omitempty\"`\n\tMaxActionsPerPeriod int                `json:\"max_actions_per_period,omitempty\"`\n\tMaxConcurrency      int                `json:\"max_concurrency,omitempty\"`\n\tMaxDelegationDepth  int                `json:\"max_delegation_depth,omitempty\"`\n\tMaxTokens           int                `json:\"max_tokens,omitempty\"`\n\tMaxSeconds          int                `json:\"max_seconds,omitempty\"`\n\tGeneratedCode       bool               `json:\"generated_code,omitempty\"`\n\tQuietHours          string             `json:\"quiet_hours,omitempty\"`\n\tExpiresAt           *time.Time         `json:\"expires_at,omitempty\"`\n\tRevoked             bool               `json:\"revoked,omitempty\"`\n}\n```\n\n```go\nfunc NarrowPolicy(parent, child DelegationPolicy) (DelegationPolicy, error)\n```\n\n```go\nfunc (p DelegationPolicy) AllowsConsequence(c ConsequenceClass, now time.Time) bool\n```\n\n```go\ntype EffectivenessEvaluation struct {\n\tProgress                               float64\n\tSuccess                                bool\n\tElapsed                                time.Duration\n\tCost                                   float64\n\tRepeatedSteps, Errors, UserCorrections int\n\tEnvironmentalInstability               bool\n\tCapabilityGap, Recommendation          string\n}\n```\n\n```go\ntype EvolutionChoice string\n```\n\n```go\nconst (\n\tEvolutionContinue       EvolutionChoice = \"continue\"\n\tEvolutionChangeStrategy EvolutionChoice = \"change_strategy\"\n\tEvolutionReuse          EvolutionChoice = \"reuse_artifact\"\n\tEvolutionGenerate       EvolutionChoice = \"generate_artifact\"\n\tEvolutionImprove        EvolutionChoice = \"improve_artifact\"\n\tEvolutionRetire         EvolutionChoice = \"retire_artifact\"\n\tEvolutionEscalate       EvolutionChoice = \"request_information_or_authority\"\n\tEvolutionAbandon        EvolutionChoice = \"abandon\"\n)\n```\n\n```go\nfunc ChooseEvolution(e EffectivenessEvaluation, hasCompatibleArtifact bool) EvolutionChoice\n```\n\n```go\ntype ExecutionEnvelope struct {\n\tTask, ExpectedOutput, CompletionCondition string\n\tContext                                   json.RawMessage\n\tToolsets                                  []string\n\tResources                                 []string\n\tConsequences                              []ConsequenceClass\n\tDeadline                                  string\n\tBudgets                                   jobs.ExecutionBudgets\n\tParentRunID, SubgoalID                    string\n\tAllowDelegation                           bool\n\tDelegationDepth                           int\n\t// BrowserSession selects the worker's browser backend when Toolsets\n\t// includes \"browser\": BrowserExistingChrome (the default for Personal\n\t// Agent delegation — the user's own already-running, already-logged-in\n\t// Chrome, reached through the gateway-owned broker) or BrowserEphemeral\n\t// (a fresh, logged-out profile — explicit opt-down only). See\n\t// docs/design/autonomous-agents.md \"Browser broker trust boundary\".\n\tBrowserSession string\n}\n```\n\n```go\ntype Executive struct {\n\tStore   *Store\n\tHome    string\n\tAgentID string\n\t// Objective is the durable outcome this wake advances, read from the\n\t// agent's configuration (gwconfig.Agent.Objective) rather than the store —\n\t// a human edits it in one place and it hot-reloads. An empty Objective\n\t// blocks the run rather than inventing one.\n\tObjective string\n\tRunner    *llm.Runner\n\tNow       func() time.Time\n\tMaxSteps  int\n\t// DelegationDepth is this wake's own depth in a delegation chain — 0 for a\n\t// top-level RunOnce/ResumeSuspended wake. A worker spawned via delegate is\n\t// itself a plain `memcode run` job, not another Executive, so depth never\n\t// grows past 1 today; the field exists so ValidateDelegation's depth check\n\t// means something even before nested Personal-Agent delegation exists.\n\tDelegationDepth int\n}\n```\nExecutive is one bounded decision loop for an agent running unattended. Each RunOnce is a single bounded wake: read durable state, run one LLM turn with domain-neutral tools, journal consequential actions, then complete, schedule the next wake, or suspend for human input. It never holds an open loop.\n\n```go\nfunc (e *Executive) ResumeSuspended(ctx context.Context, in Interaction, answer string) (RunOutcome, error)\n```\nResumeSuspended continues a suspended run after its interaction is answered. It loads the saved transcript, appends the exact tool\\_result for the suspended tool\\_use\\_id, then re-enters the bounded loop so the model actually continues — no replay of completed actions, no fabricated user turn. It marks the continuation resolved ONLY after the resumed run finishes, so a failure leaves the interaction retryable.\n\n```go\nfunc (e *Executive) RunOnce(ctx context.Context) (RunOutcome, error)\n```\nRunOnce executes a single bounded wake for the agent's primary objective. It fails closed: no approved policy, inactive objective, or an expired/revoked policy all block consequential work before any LLM call is made.\n\n```go\ntype ExecutiveDecision struct {\n\tKind, SubgoalID, Reason string\n\tNextWake                *time.Time\n}\n```\n\n```go\nfunc EvaluateEffectiveness(e EffectivenessEvaluation) ExecutiveDecision\n```\n\n```go\nfunc SelectNextAction(state ExecutiveState, now time.Time) ExecutiveDecision\n```\n\n```go\ntype ExecutiveState struct {\n\tObjective           Objective\n\tSubgoals            []Subgoal\n\tPendingInteractions int\n\tRecentActions       []Action\n\tLastEvaluation      *EffectivenessEvaluation\n}\n```\n\n```go\ntype GeneratedIndex struct {\n\tPath, Hash, Purpose, SourceObjectiveID, SourceRunID, ParentRevision string\n\tBuildCommand, RunCommand, TestCommand                               []string\n\tEvaluations                                                         []EffectivenessEvaluation\n\tActiveRevision                                                      string\n}\n```\n\n```go\ntype GeneratedItem struct {\n\tID, ObjectiveID, Path, Hash, Purpose, SourceRunID, ParentRevision, ActiveRevision string\n\tInvocation, Evaluations                                                           json.RawMessage\n\tLastUsedAt                                                                        *time.Time\n\tCreatedAt, UpdatedAt                                                              time.Time\n}\n```\n\n```go\ntype Interaction struct {\n\tID, AgentID, ObjectiveID, RunID string\n\tKind, Question, Context         string\n\tAnswer                          *string\n\tStatus                          string // pending | answered | cancelled\n\tToolUseID                       string\n\tCreatedAt                       time.Time\n\tAnsweredAt                      *time.Time\n}\n```\nInteraction is a durable human-in-the-loop request created by a suspending tool (ask\\_user). It lives in the agent's personal.db and is answered via \\`personal answer\\`. Resume is exact: the saved tool\\_use\\_id gets the answer.\n\n```go\ntype MissedRunPolicy string\n```\n\n```go\nconst (\n\tMissedSkip    MissedRunPolicy = \"skip\"\n\tMissedRunOnce MissedRunPolicy = \"run_once\"\n\tMissedCatchUp MissedRunPolicy = \"catch_up\"\n)\n```\n\n```go\ntype Notification struct {\n\tID, ObjectiveID, Kind, Status string\n\tPayload                       json.RawMessage\n\tCreatedAt, UpdatedAt          time.Time\n}\n```\n\n```go\ntype Objective struct {\n\tID, Description, SuccessCriteria, Status string\n\tPriority                                 int\n\tCreatedAt, UpdatedAt                     time.Time\n\tReviewAt                                 *time.Time\n}\n```\n\n```go\ntype PacePolicy struct {\n\tBurstCap, PeriodLimit, Concurrency       int\n\tMinimumCooldown, BaseBackoff, MaxBackoff time.Duration\n\tQuietStart, QuietEnd                     int\n}\n```\n\n```go\ntype PaceState struct {\n\tPeriodStarted                time.Time\n\tActions, ConsecutiveFailures int\n\tCooldownUntil                time.Time\n\tSuspended                    bool\n\tWarning                      string\n}\n```\n\n```go\nfunc (s PaceState) AfterFailure(now time.Time, p PacePolicy, warning bool) PaceState\n```\n\n```go\nfunc (s PaceState) AfterSuccess(now time.Time, p PacePolicy) PaceState\n```\n\n```go\nfunc (s PaceState) Allow(now time.Time, p PacePolicy) bool\n```\n\n```go\ntype Policy struct {\n\tID, ObjectiveID, Hash, Status string\n\tVersion                       int\n\tDocument                      json.RawMessage\n\tApprovedAt                    *time.Time\n\tCreatedAt                     time.Time\n}\n```\n\n```go\ntype Resource struct {\n\tID, ObjectiveID, Type, Locator, AccessMode, AuthorizationSource, PolicyHash, Status string\n\tConstraints                                                                         json.RawMessage\n\tExpiresAt                                                                           *time.Time\n\tCreatedAt, UpdatedAt                                                                time.Time\n}\n```\n\n```go\ntype ResourceGrantModel struct {\n\tID                                      string\n\tType                                    ResourceType\n\tLocator, AccessMode                     string\n\tConstraints                             map[string]any\n\tAuthorizationSource, PolicyHash, Status string\n\tExpiresAt                               *time.Time\n}\n```\n\n```go\nfunc (g ResourceGrantModel) Active(now time.Time) bool\n```\n\n```go\ntype ResourceType string\n```\n\n```go\nconst (\n\tResourceFilesystem       ResourceType = \"filesystem\"\n\tResourceBrowser          ResourceType = \"browser\"\n\tResourceMCP              ResourceType = \"mcp\"\n\tResourceCommand          ResourceType = \"command\"\n\tResourceRepository       ResourceType = \"repository\"\n\tResourceCloud            ResourceType = \"cloud\"\n\tResourceDocument         ResourceType = \"document\"\n\tResourceChannel          ResourceType = \"channel\"\n\tResourceGeneratedProcess ResourceType = \"generated_process\"\n)\n```\n\n```go\ntype Run struct {\n\tID, ObjectiveID, SubgoalID, ParentRunID, SessionID string\n\tEnvelope, Outcome, Evidence                        json.RawMessage\n\tStatus                                             string\n\tCreatedAt, UpdatedAt                               time.Time\n}\n```\n\n```go\ntype RunOutcome struct {\n\tRunID         string     `json:\"run_id\"`\n\tStatus        string     `json:\"status\"`\n\tReport        string     `json:\"report\"`\n\tNextWakeAt    *time.Time `json:\"next_wake_at,omitempty\"`\n\tInteractionID string     `json:\"interaction_id,omitempty\"`\n}\n```\n\n```go\ntype RunResult struct {\n\tStdout, Stderr string\n\tExitCode       int\n\tChangedFiles   []string\n}\n```\n\n```go\nfunc RunGenerated(ctx context.Context, s RunSpec) (RunResult, error)\n```\n\n```go\ntype RunSpec struct {\n\tExecutable             string\n\tArgs                   []string\n\tInputs                 map[string][]byte\n\tAllowedExecutables     []string\n\tTimeout                time.Duration\n\tMaxOutputBytes         int\n\tEnvironment            map[string]string\n\tRequireHardenedSandbox bool\n}\n```\n\n```go\ntype Store struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc Open(ctx context.Context, home string) (*Store, error)\n```\n\n```go\nfunc (s *Store) ActionForJob(ctx context.Context, jobID string) (string, error)\n```\nActionForJob returns the id of the action that spawned jobID, or \"\" when there is none.\n\n```go\nfunc (s *Store) ApprovePolicy(ctx context.Context, hash string) error\n```\n\n```go\nfunc (s *Store) ApprovedPolicy(ctx context.Context, objectiveID string) (Policy, bool, error)\n```\n\n```go\nfunc (s *Store) CancelInteraction(ctx context.Context, id string) error\n```\n\n```go\nfunc (s *Store) CancelPendingNotifications(ctx context.Context) error\n```\n\n```go\nfunc (s *Store) ClaimDueTrigger(ctx context.Context, id string, now time.Time) (Trigger, bool, error)\n```\n\n```go\nfunc (s *Store) Close() error\n```\n\n```go\nfunc (s *Store) CompleteAction(ctx context.Context, id string, status ActionStatus, result, evidence json.RawMessage) error\n```\n\n```go\nfunc (s *Store) CreateObjective(ctx context.Context, o Objective) error\n```\n\n```go\nfunc (s *Store) CreateRun(ctx context.Context, r Run) error\n```\n\n```go\nfunc (s *Store) CreateTrigger(ctx context.Context, t Trigger) error\n```\n\n```go\nfunc (s *Store) DB() *sql.DB\n```\nDB exposes the underlying handle for store-internal submodules (same package); external callers use Store methods only.\n\n```go\nfunc (s *Store) DeleteObjective(ctx context.Context, id string) error\n```\n\n```go\nfunc (s *Store) DueTriggers(ctx context.Context, now time.Time) ([]Trigger, error)\n```\nDueTriggers returns only enabled triggers whose next\\_due\\_at has passed, filtered in SQL rather than pulling every trigger row (including completed ones) and filtering in Go on every poll.\n\n```go\nfunc (s *Store) GetInteraction(ctx context.Context, id string) (Interaction, bool, error)\n```\n\n```go\nfunc (s *Store) GetObjective(ctx context.Context, id string) (Objective, bool, error)\n```\n\n```go\nfunc (s *Store) InsertInteraction(ctx context.Context, in Interaction) error\n```\n\n```go\nfunc (s *Store) InsertNotification(ctx context.Context, n Notification) error\n```\n\n```go\nfunc (s *Store) InsertPolicy(ctx context.Context, p Policy) error\n```\n\n```go\nfunc (s *Store) InsertResource(ctx context.Context, r Resource) error\n```\n\n```go\nfunc (s *Store) LinkActionJob(ctx context.Context, actionID, jobID string) error\n```\nLinkActionJob records which detached job an action spawned, so a later wake can find its way back from a job id to the action it must close out.\n\n```go\nfunc (s *Store) ListActions(ctx context.Context, objectiveID string, limit int) ([]Action, error)\n```\n\n```go\nfunc (s *Store) ListObjectives(ctx context.Context) ([]Objective, error)\n```\n\n```go\nfunc (s *Store) ListPolicies(ctx context.Context, objectiveID string) ([]Policy, error)\n```\n\n```go\nfunc (s *Store) ListResources(ctx context.Context, objectiveID string) ([]Resource, error)\n```\n\n```go\nfunc (s *Store) ListRuns(ctx context.Context, objectiveID string, limit int) ([]Run, error)\n```\n\n```go\nfunc (s *Store) ListSubgoals(ctx context.Context, objectiveID string) ([]Subgoal, error)\n```\n\n```go\nfunc (s *Store) ListTriggers(ctx context.Context) ([]Trigger, error)\n```\n\n```go\nfunc (s *Store) MarkActionRunning(ctx context.Context, id string) error\n```\n\n```go\nfunc (s *Store) NextPolicyVersion(ctx context.Context, objectiveID string) (int, error)\n```\n\n```go\nfunc (s *Store) PendingInteractions(ctx context.Context, agentID string) ([]Interaction, error)\n```\n\n```go\nfunc (s *Store) RecoverableRuns(ctx context.Context) ([]Run, error)\n```\n\n```go\nfunc (s *Store) ReserveAction(ctx context.Context, a ActionIntent) (Action, bool, error)\n```\n\n```go\nfunc (s *Store) ResolveInteraction(ctx context.Context, id, answer string) error\n```\nResolveInteraction atomically marks a pending interaction answered. Returns an error if it was already resolved (prevents double-resume of a suspended run).\n\n```go\nfunc (s *Store) ResolveUncertainAction(ctx context.Context, id string, status ActionStatus) error\n```\n\n```go\nfunc (s *Store) RevokeResources(ctx context.Context, objectiveID string) error\n```\n\n```go\nfunc (s *Store) SetObjectiveStatus(ctx context.Context, id, status string) error\n```\n\n```go\nfunc (s *Store) SetObjectiveText(ctx context.Context, id, description string) error\n```\nSetObjectiveText updates an objective's description (the user-authored goal).\n\n```go\nfunc (s *Store) SetResourceStatus(ctx context.Context, id, status string) error\n```\n\n```go\nfunc (s *Store) SetSubgoalStatus(ctx context.Context, id, status string) error\n```\n\n```go\nfunc (s *Store) StatusSummary(ctx context.Context) (map[string]int, error)\n```\n\n```go\nfunc (s *Store) UpdateRunStatus(ctx context.Context, id, status string, outcome json.RawMessage) error\n```\n\n```go\nfunc (s *Store) UpsertSubgoal(ctx context.Context, g Subgoal) error\n```\n\n```go\ntype Subgoal struct {\n\tID, ObjectiveID, ParentID, Description, Status, Rationale string\n\tPriority                                                  int\n\tDependencies                                              json.RawMessage\n\tCreatedAt, UpdatedAt                                      time.Time\n}\n```\n\n```go\ntype Trigger struct {\n\tID, ObjectiveID, Kind, Spec, MissedRunPolicy, Status string\n\tNextDueAt, LastFiredAt                               *time.Time\n\tCreatedAt, UpdatedAt                                 time.Time\n}\n```\n\n","path":"github.com/memcode-ai/memcode/internal/agent/autonomy","name":"autonomy","synopsis":"Package personal implements the domain-general durable state and runtime primitives for autonomous agents.","isRedistributable":true}
