Skip to content

Worklogs: license-gated append-only logs scoped to a factory #1297

Closed

Description

@jpshackelford

Summary

Add worklogs to OpenHands Enterprise: named, append-only logs scoped to a factory, written to with a raw-body POST by automation runs and by humans. A worklog is a license-gated Enterprise feature, available on OpenHands Cloud and OpenHands Enterprise installs.

Factories themselves (a named group of automations) live in the automation service: OpenHands/automation#725. This issue adds the worklog data model and API in this repo, keyed by a factory id. Automation-side support (the run token, the factory lookup and the delete notification) is tracked in OpenHands/automation#726. The Factory UI is a companion issue in OpenHands/OpenHands.

Why

Orchestration setups that coordinate several automations currently keep their coordination state in a WORKLOG.md committed to the target repository: an append-only record of what was launched and why, plus ## INSTRUCTION: entries that a human leaves for the orchestrator to read on its next wake-up. It has to be truncated by hand once it grows, and it pollutes the repository history.

Worklogs give that coordination state a proper home. They belong here, not in the automation service, because:

  • The automation service owns definitions, scheduling, webhooks, run history and dispatch. A human-facing narrative store is outside that charter.
  • Enterprise owns organizations, roles and permissions, licensing and rate limiting, which a worklog needs.
  • Enterprise is where a conversation's credentials come from, so the later step of letting agents write from inside a conversation needs this repo in any case.

Terminology

Concept Name in API, DB and UI Replaces
Grouping of automations Factory (automation#725) unchanged
Named append-only log inside a factory Worklog "event stream", "work stream", streams
One record in a worklog Entry "event"
Who wrote an entry author "author or source label"
Entry heading shown in lists title "title"
Payload format content_type = markdown | json unchanged
First worklog every factory gets default (displayed "Default")

Do not use event, stream or bare log for worklog data in code, routes, tables or UI strings. They already mean something else: SDK conversation events and shared events here, inbound webhook events and stream sources in the automation service, and application, run and OTEL logs everywhere. orchestrator and worker are conventions of particular plugins, not platform nouns, so they do not appear in schemas.

Requirements

Data model

One Alembic migration (current head is 213), PostgreSQL.

  • worklogs: id, org_id (references org.id, ON DELETE CASCADE), factory_id (a plain UUID with no foreign key, because factories live in the automation service's database), slug, name, is_default, created_at, updated_at.
    • slug and name are each unique within (org_id, factory_id). The slug is the identifier in URLs and is immutable. Rename changes only name.
    • A partial unique index on (org_id, factory_id) WHERE is_default allows at most one default worklog per factory.
  • worklog_entries: id, worklog_id (ON DELETE CASCADE), created_at (server-assigned), content_type, title (nullable), author_kind (user | automation), author_id (nullable), author_name (nullable), run_id (nullable), body (text, opaque). Index on (worklog_id, created_at, id).

Entries are append-only. There is no update or delete route. Entry bodies are stored as plaintext. Worklogs are narrative and are not a place for secrets; the API documentation says so.

Addressing

Routes address a factory by its id. Slugs exist only in the automation service, and Canvas already has the id from the factory response.

Default worklog

  • A factory's default worklog is created lazily on the first access to that factory's worklogs, with INSERT ... ON CONFLICT DO NOTHING so two concurrent first requests produce one.
  • On the user-auth path, the first access first confirms the factory exists in the org by asking the automation service (see "Factory lookup"). An unknown factory returns 404. Any failure reaching the automation service returns 503, so the check fails closed.
  • On the run-token path no lookup is needed: the automation service signed the token while the factory existed.
  • The default worklog is an ordinary worklog and can be renamed. The current default cannot be deleted; DELETE returns 409. To change the default, PATCH another worklog with is_default: true. The swap happens in one transaction. is_default: false is rejected with 422.
  • When no worklog is named, the request targets the default worklog. When a worklog is named but unknown, the request returns 404. A mistyped name never falls back to the default.

API (user auth)

Under /api/organizations/{org_id}/factories/{factory_id}:

  • POST /worklogs, GET /worklogs, PATCH /worklogs/{worklog} (rename, make default), DELETE /worklogs/{worklog}.
    • GET /worklogs returns, for each worklog, entry_count, json_entry_count and last_entry_at. The UI needs these for the worklog picker and the "Show JSON entries (N hidden)" toggle.
  • POST /worklogs/{worklog}/entries
    • The body is the raw request body, not a field in a JSON envelope. Content-Type is text/markdown or application/json. Any other type returns 415.
    • The server assigns created_at. The caller sends no wrapper and no escaping.
    • Markdown is stored verbatim. Markdown that contains JSON in code fences is safe because nothing parses it.
    • JSON is validated on write and stored as the received string, not re-serialized. Invalid JSON returns 422 with the parse error and position, so a writer can fix it in one retry.
    • Invalid UTF-8 returns 422. A body over the size limit returns 413.
    • Response is 201 with the entry id and created_at.
  • GET /worklogs/{worklog}/entries?since=&limit=&content_type=
    • Returns id, created_at, content_type, title, author ({kind, id, name}), run_id and body (a string).
    • Order is (created_at, id). The paging cursor encodes both values so entries that share a timestamp are neither skipped nor repeated.
    • content_type filters to markdown or json.
  • The default-worklog forms of the entry routes omit /worklogs/{worklog}: /entries.

Summaries for the factory cards: GET /api/organizations/{org_id}/worklog-summaries?factory_id=... (repeatable, at most 100) returns, for each requested factory, worklog_count, entry_count and last_entry_at. It reads only existing rows and does not create default worklogs, so a never-used factory reports zeros.

API (run token)

These routes are under /api/service/worklog, which the middleware already exempts from session and API-key authentication. They accept a run token only (Authorization: Bearer ...). The factory comes from the token's claims, so a run needs no ids in its URLs:

  • GET /api/service/worklog: the factory's worklogs.
  • GET and POST /api/service/worklog/entries: the default worklog.
  • GET and POST /api/service/worklog/{worklog}/entries: a named worklog.

They behave like the user-auth entry routes in every other respect.

Run token

The automation service mints it at dispatch (OpenHands/automation#726); this repo verifies it.

  • JWT, HS256. The signing key is derived from AUTOMATIONS_SERVICE_KEY with HKDF-SHA256 and the fixed info string openhands-factory-run-token-v1. The raw service key is never used as the signing key. No new secret is introduced, because both services already hold this key.
  • Claims: aud = factory, org_id, factory_id, automation_id, automation_name (at most 256 characters), run_id, iat, exp (24 hours after issue).
  • Enterprise verifies the signature, aud and exp only. It makes no call to the automation service. The token is a general factory run token, not a worklog-specific credential. Enterprise accepts it only on the worklog routes, where it reaches one factory's worklogs and nothing else.
  • When AUTOMATIONS_SERVICE_KEY is unset, the run-token routes return 503, as the service routes do. The user-auth routes are unaffected.
  • A fixed test vector (key, claims, resulting token) is committed in the tests of both repos as the contract.

Factory lookup

Enterprise confirms a factory exists with a service-key request to the automation service. The endpoint is added by OpenHands/automation#726. It returns, for up to 100 ids and one org, the ids that exist. This uses AUTOMATION_SERVICE_URL and AUTOMATIONS_SERVICE_KEY, as the existing automation checks do.

Factory deletion and cleanup

  • POST /api/service/orgs/{org_id}/factories/{factory_id}/deleted authenticates with X-Service-API-Key, removes the factory's worklogs and entries, is idempotent and returns 204. The automation service calls it after deleting a factory. It is a notification that the factory is gone, so it is not named for worklogs; removing worklogs is what Enterprise does in response. It is not license-gated, so cleanup always works.
  • A maintenance task (server/maintenance_task_processor) removes the worklogs of factories that no longer exist, using the batched factory lookup, so a missed notification is repaired. It is not license-gated.
  • Deleting an org removes its worklogs and entries through the foreign key.
  • delete_user_data anonymizes authorship: it sets author_id to NULL on entries where author_kind = 'user' and author_id is the deleted user. The entries stay, because they belong to the retained organization.

Authorization

Operation Who
Read worklogs and entries; worklog summaries Any org member (VIEW_AUTOMATIONS)
Write entries; create, rename or delete worklogs; change the default MANAGE_AUTOMATIONS (admin and owner)
Read and write the run's own factory through /api/service/worklog/... A run token
  • No new Permission values or role changes are needed. Service accounts hold only VIEW_AUTOMATIONS, so they write through the run token.
  • Writing entries needs MANAGE_AUTOMATIONS because an entry such as INSTRUCTION: can steer an orchestrator.
  • {org_id} in the path is bound by require_permission, including the existing API-key org binding.
  • Author is set by the server and cannot be supplied by the caller. A run token records author_kind = automation, author_id = the automation id, author_name = the automation_name claim, and the run_id. A user records author_kind = user and author_id = the user id, with author_name null; Canvas resolves user names.

License gating

  • Add worklogs to LicenseFeature, to LicenseFeatures (default False) and to LicenseFeaturesResponse, so GET /license/status reports it. has_feature already returns True while enforcement is off.
  • Every user-auth and run-token worklog route uses require_feature('worklogs'). A license without it gets 403. The deleted-factory route and the maintenance task are exempt.
  • Whoever issues licenses must be able to grant the feature. That is outside this repo.
  • Clients treat 403, 404 and 503 from the worklog routes as "worklogs unavailable". Automation scripts keep running when a worklog write fails, because an unlicensed install must not break runs.

Limits

  • Maximum entry size is 64 KiB by default, configurable with WORKLOG_MAX_ENTRY_BYTES.
  • Entry writes are rate limited per (org_id, factory_id) with the existing Redis limiter, configured by WORKLOG_WRITE_RATE_LIMIT, default 10/second; 300/minute. Exceeding it returns 429 with Retry-After. An empty value or RATE_LIMITING_ENABLED=false disables it, and a Redis failure lets the write through, as the limiter does everywhere else. The default values are starting points for tuning, not measured limits.
  • There is no retention or TTL.

Out of scope

  • The Factory object, automations.factory_id and the factory API (automation#725).
  • The run token minting, the factory lookup endpoint and the delete notification on the automation side (automation#726).
  • The Factory UI (companion issue in OpenHands/OpenHands).
  • Editing or deleting entries, instruction acknowledgement, and cross-factory queries.
  • Writing from inside an agent conversation. This needs a conversation-scoped credential issued by the app server, plus a factoryid tag on automation-started conversations (they already carry automationid and automationrunid). It is separate work.
  • Worklogs on a local Agent Canvas install, which has no Enterprise server.

Acceptance criteria

Worklogs

  • The first access to a factory's worklogs creates exactly one default worklog, even under concurrent first requests, and it is the factory's default. More worklogs can be added. A worklog's slug cannot be changed.
  • On the user-auth path, an unknown factory returns 404, and a failure reaching the automation service returns 503. The run-token path makes no call to the automation service.
  • The default worklog cannot be deleted. Making another worklog the default swaps the default in one transaction. Renaming the default does not change which worklog is the default. is_default: false returns 422.
  • GET .../worklogs returns entry_count, json_entry_count and last_entry_at for each worklog. worklog-summaries returns worklog_count, entry_count and last_entry_at for each requested factory and creates nothing.

Entries

  • Posting raw markdown that contains fenced JSON succeeds on the first try, and the body reads back byte-identical, including CRLF line endings and non-ASCII text.
  • Posting valid JSON succeeds and reads back as the same string. Invalid JSON returns 422 with the parse error. An unsupported content type returns 415, invalid UTF-8 returns 422, and a body over the limit returns 413.
  • A markdown entry beginning ## INSTRUCTION: ... gets the title INSTRUCTION: .... An entry with no heading gets its first non-empty line, truncated to 120 characters. An X-Worklog-Title header overrides the derived title for both content types. JSON entries have no derived title.
  • Entries list in (created_at, id) order with working paging, including pages that cross entries with identical timestamps. content_type filters the list.
  • A request without a worklog name uses the default worklog. A request with an unknown worklog name returns 404.
  • No route updates or deletes an entry.
  • Writes beyond WORKLOG_WRITE_RATE_LIMIT return 429 with Retry-After, and the limit is off when the setting is empty.

Authorization and licensing

  • Any org member can read. A caller without MANAGE_AUTOMATIONS gets 403 on writing entries and on worklog management.
  • A run token can read and write only its own factory's worklogs, through /api/service/worklog/.... Missing, expired, wrongly signed or wrong-aud tokens return 401. A user session or API key on those routes is rejected. With AUTOMATIONS_SERVICE_KEY unset they return 503.
  • The test vector from the contract verifies in this repo's tests.
  • author cannot be set by the caller. An entry written with a run token records the automation's id and name and the run_id. An entry written by a user records the user id and a null name.
  • A license without worklogs gets 403 on every worklog route. With enforcement off, the routes work. GET /license/status reports the feature.

Cleanup

  • The deleted-factory route removes a factory's worklogs and entries, returns 204, and returns 204 again when repeated. It needs X-Service-API-Key.
  • The maintenance task removes the worklogs of a factory that the lookup reports as gone, and leaves the others.
  • Deleting an org removes its worklogs and entries. Deleting a user sets author_id to NULL on that user's entries and keeps them.

Other

  • One Alembic head with a complete upgrade path, and tests use the PostgreSQL fixtures.

Notes for implementation

  • Related existing work in this repo: the service routes and shared key in server/routes/service.py (the /api/service/ auth exemption is in server/middleware.py), org-scoped routes and permissions in server/routes/org_mcp_servers.py and server/auth/authorization.py, the license feature gate in server/licensing/service.py, the rate limiter in server/rate_limit.py, the cross-service check pattern in _owns_automation (server/routes/service_accounts.py), and the user purge in storage/user_data_cleanup.py.
  • Rollout order: the automation service first (it can mint tokens before this repo accepts them), then this repo, then Canvas. Enterprise pins an automation image tag, so the verifier must not ship ahead of the dispatcher that mints the token.

This issue was created by an AI agent (OpenHands) on behalf of @jpshackelford.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions