Repository navigation
Description
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(referencesorg.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.slugandnameare each unique within(org_id, factory_id). The slug is the identifier in URLs and is immutable. Rename changes onlyname.- A partial unique index on
(org_id, factory_id) WHERE is_defaultallows 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
defaultworklog is created lazily on the first access to that factory's worklogs, withINSERT ... ON CONFLICT DO NOTHINGso 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 returns503, 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;
DELETEreturns409. To change the default,PATCHanother worklog withis_default: true. The swap happens in one transaction.is_default: falseis rejected with422. - 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 /worklogsreturns, for each worklog,entry_count,json_entry_countandlast_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-Typeistext/markdownorapplication/json. Any other type returns415. - 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
422with 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 returns413. - Response is
201with the entryidandcreated_at.
- The body is the raw request body, not a field in a JSON envelope.
GET /worklogs/{worklog}/entries?since=&limit=&content_type=- Returns
id,created_at,content_type,title,author({kind, id, name}),run_idandbody(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_typefilters tomarkdownorjson.
- Returns
- 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.GETandPOST /api/service/worklog/entries: the default worklog.GETandPOST /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_KEYwith HKDF-SHA256 and the fixed info stringopenhands-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,
audandexponly. 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_KEYis unset, the run-token routes return503, 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}/deletedauthenticates withX-Service-API-Key, removes the factory's worklogs and entries, is idempotent and returns204. 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_dataanonymizes authorship: it setsauthor_idtoNULLon entries whereauthor_kind = 'user'andauthor_idis 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
Permissionvalues or role changes are needed. Service accounts hold onlyVIEW_AUTOMATIONS, so they write through the run token. - Writing entries needs
MANAGE_AUTOMATIONSbecause an entry such asINSTRUCTION:can steer an orchestrator. {org_id}in the path is bound byrequire_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= theautomation_nameclaim, and therun_id. A user recordsauthor_kind = userandauthor_id= the user id, withauthor_namenull; Canvas resolves user names.
License gating
- Add
worklogstoLicenseFeature, toLicenseFeatures(defaultFalse) and toLicenseFeaturesResponse, soGET /license/statusreports it.has_featurealready returnsTruewhile enforcement is off. - Every user-auth and run-token worklog route uses
require_feature('worklogs'). A license without it gets403. 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,404and503from 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 byWORKLOG_WRITE_RATE_LIMIT, default10/second; 300/minute. Exceeding it returns429withRetry-After. An empty value orRATE_LIMITING_ENABLED=falsedisables 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_idand 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
factoryidtag on automation-started conversations (they already carryautomationidandautomationrunid). 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
defaultworklog, 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 returns503. 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: falsereturns422. GET .../worklogsreturnsentry_count,json_entry_countandlast_entry_atfor each worklog.worklog-summariesreturnsworklog_count,entry_countandlast_entry_atfor 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
422with the parse error. An unsupported content type returns415, invalid UTF-8 returns422, and a body over the limit returns413. - A markdown entry beginning
## INSTRUCTION: ...gets the titleINSTRUCTION: .... An entry with no heading gets its first non-empty line, truncated to 120 characters. AnX-Worklog-Titleheader 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_typefilters 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_LIMITreturn429withRetry-After, and the limit is off when the setting is empty.
Authorization and licensing
- Any org member can read. A caller without
MANAGE_AUTOMATIONSgets403on 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-audtokens return401. A user session or API key on those routes is rejected. WithAUTOMATIONS_SERVICE_KEYunset they return503. - The test vector from the contract verifies in this repo's tests.
authorcannot be set by the caller. An entry written with a run token records the automation's id and name and therun_id. An entry written by a user records the user id and a null name.- A license without
worklogsgets403on every worklog route. With enforcement off, the routes work.GET /license/statusreports the feature.
Cleanup
- The deleted-factory route removes a factory's worklogs and entries, returns
204, and returns204again when repeated. It needsX-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_idtoNULLon 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 inserver/middleware.py), org-scoped routes and permissions inserver/routes/org_mcp_servers.pyandserver/auth/authorization.py, the license feature gate inserver/licensing/service.py, the rate limiter inserver/rate_limit.py, the cross-service check pattern in_owns_automation(server/routes/service_accounts.py), and the user purge instorage/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.
Activity
refactor(factories): make the run token and delete notification gener…
feat(factories): add the Factory model and automation link (#751)
feat(factories): add the run token, factory lookup and delete notific…
feat(factories): show a factory's worklogs, newest first (#19811)
feat(factories): delete a factory from its page (#19861)
feat(worklogs): add license-gated, append-only worklogs scoped to a f…