Contracts
Changes that cross repositories (schema, validator, kernel contracts, connector format) start as a numbered contract in docs/contracts/ (how contracts change). "Proposed" contracts may already be built in part; each file says what shipped.
| No. | Contract | Status |
|---|---|---|
| 0000 | How contracts change | proposed |
| 0001 | Modules and apps | accepted |
| 0002 | Connector runtime and ports | proposed |
| 0003 | Edge agent and devices | proposed |
| 0004 | App packages and upgrades | accepted in principle |
| 0005 | Pilot readiness | accepted |
| 0006 | Edge sync (edge-sync/v1) | proposed |
| 0007 | Document approvals | proposed |
| 0008 | Print formats | proposed |
| 0009 | Number schemes | proposed |
| 0010 | Multi-org and row scope | proposed |
| 0011 | Attachments | proposed |
| 0012 | Imports | proposed |
| 0013 | Money and currency | proposed |
| 0014 | Process canvas | proposed |
| 0015 | Ubah mode and live preview | proposed |
| 0016 | Site company module | proposed |
| 0017 | Connector secrets | proposed |
| 0018 | List aggregates | accepted |
| 0019 | Default shell: side-only | accepted |
| 0020 | AI assistant relay | proposed |
| 0021 | Declarative stock moves | implemented |
| 0022 | Unit conversion and returned quantities | implemented |
| 0024 | List and dashboard export | proposed |
| 0025 | Check-then-write in flows | accepted |
| 0026 | Append-only ledgers | accepted |
| 0027 | Field visibility (hidden_for) and dashboard roles | accepted |
| 0028 | Plan limits | accepted |
| 0029 | XML file formats | proposed |
| 0030 | Work screens (staff tools declared in .rk) | accepted |
| 0031 | Recurring documents: month arithmetic and for_each | accepted |
| 0032 | Free module composition | proposed |
| 0033 | AI-drafted company pieces and connectors | proposed |
| 0034 | Counter: dry compute, summary and availability | proposed |
| 0035 | Rangka skills: one Agent Skills library for Raka and any other harness | accepted |
| 0036 | Catalogue in the platform: modules and connectors | proposed |
| 0037 | Nested navigation: sub-levels in menus and nav.side | accepted and implemented |
| 0038 | Responsive behaviour in layout.rk | accepted and implemented |
| 0039 | Counter: stock per outlet on the catalogue | proposed |
The base contract (v0) follows.
Shared agreements between rangka-os (kernel, Console), rangka-ai and rangka-apps. Everything here is v0: change it only by editing this file in a pull request, and update both validators and the affected clients in the same change.
Repositories (cloned side by side)
| Repo | Contains | Language |
|---|---|---|
rangka-os/ | schema/0.4/*.json (all .rk schemas), tools/ (Python reference validator rangka_validate.py, strict YAML reader rkfile.py, docs + prototype builders), templates/ (theme + layout templates), web/design-system/ (bundle.js/css, tokens.json, index.d.ts), web/app/ (end-user web app), docs/site/ (API docs page), kernel/ (Go, new), web/console/ (Console, new) | Go, JS, Python tools |
rangka-apps/ | apps/{core,sales,crm} (app.rk, models, dashboards, flows, roles), fixtures/*.rk, templates/crm, sites/kopi-senja/ (an installation: system.rk, features.rk, config.rk, themes/, layouts/) | .rk |
rangka-connectors/ | whatsapp_business/connector.rk | .rk |
rangka-ai/ | Agent (new) | TypeScript (Node 20+) |
Layers
0 deploy targets · 1 kernel · 2 system capabilities (system.rk) · 3 integrations (connectors) · 4 organisation (features.rk, config.rk, orgs/members in DB) · 5 apps (apps/*) · 6 presentation (themes/*.rk, layouts/*.rk). Rangka AI may write layers 4–6 through change sets only. Layer 2 changes, secrets, roles/permissions = admin approval.
.rk files
Strict YAML (see rangka-os/tools/rkfile.py docstring): YAML 1.2 core types; refuse unquoted yes/no/on/off/y/n, leading-zero numbers, 1_000, 08:30; refuse duplicate keys, tabs, anchors/aliases, merge keys. ${ENV} must be quoted inside flow mappings (url: '${DATABASE_URL}'). First line # yaml-language-server: $schema=https://rangka-os.github.io/rangka-os/schema/0.4/<kind>.json names the kind. Kinds: app, model, dashboard, flow, system, theme, layout, features, config, changeset, (connector, role, template, fixtures: no schema yet).
Reference implementation of "meaning" checks: rangka-os/tools/rangka_validate.py (run python3 rangka-os/tools/rangka_validate.py rangka-apps/apps → 0 errors). The Go kernel must reproduce its error codes (unknown_field, unknown_model, bad_field_type, compute_cycle, …) and report file:line:col.
CEL dialect (rules, compute, defaults, depends_on, filters, flows)
Operators == != < <= > >= && || ! + - * / %, ternary, in, member access on link fields (customer.payment_days loads the linked record), list literals. Functions: today() (ISO date string, org timezone), now(), duration('7d'), date ± duration → date, round(x), size(x), sum(list), list.map(x, expr), option('field', 'attr') (attribute of the selected option of a select field, e.g. probability), app_installed('sales'), truncate(s, n), s.contains(t), add_months(date, n) (a YYYY-MM-DD date n calendar months later, the day clamped to the end of the target month: 2026-01-31 + 1 = 2026-02-28; add to an anchor, never to the previous result) and days_between(a, b) (whole days from a to b, negative when b is earlier, 0 when either is empty; contract 0031), epoch(t) (a datetime or YYYY-MM-DD date as whole Unix seconds, null when empty), timestamp(n) (Unix seconds as an RFC 3339 UTC datetime, null when empty), for poll cursors (contract 0002), and distance_m(a, b) (metres between two geo positions, 1e9 when either has none, so a radius check fails without a position; contract 0030 §4). Globals: user (user.name, user.roles), org and tax (the current org's PKP status and PPN figures, contract 0010 §8), event (flows). Dates are ISO strings and compare as strings. Missing values are '' for data/date/link, 0 for numbers, false for check.
Records and lifecycle
Every model → table r_<model> with typed columns (+ org_id, name PK per org, docstatus 0/1/2 for submittable, amended_from, owner, created_at, modified_at, x JSONB for company-layer x_ fields). Table fields (type: table) → child table r_<child_model> with parent, parent_field, idx. Submittable: create as draft with name DRAFT-xxxx; naming pattern applied at submit (INV-{YYYY}-{#####} per org); submitted (1) is immutable (409); cancel → 2; amend → new draft with amended_from (a unique value still held, e.g. by the cancelled original, is a 422 unique issue, as on create). Submit renames DRAFT-xxxx and every link to it (link fields, child rows, x_ link fields) follows. Delete is 409 linked while a record that is not cancelled still links the record (a link field, a child row, an x_ link field; a self link does not count); the message names that record only to someone who may read it. Rules run on save and submit; level: warn returns warnings, error blocks. A rule whose check cannot be evaluated counts as failed (code: rule_error, the message says it could not be checked): an error rule blocks, a warn rule warns. Computed fields recomputed on every save. Status for invoices: draft, submitted, partly, paid, overdue, cancelled (see rangka-os/web/app/engine.js status()).
REST (JSON, /api/v1)
| Method | Path | Notes |
|---|---|---|
| GET | /meta | {apps:[{name,version,title,menu,dashboards}], models:{…}, dashboards:{…}, theme:{name,mode,tokens:{light:{},dark:{}}}, layout:{…}} |
| GET | /r/{model} | ?filter=<CEL>&sort=-field&limit=50&offset=0&q=text → {data, total} |
| POST | /r/{model} | create → 201 record; 422 {errors:[{field,code,message}], warnings:[…]} |
| GET/PATCH/DELETE | /r/{model}/{name} | PATCH merges; 409 when submitted |
| POST | /r/{model}/{name}/{submit,cancel,amend} | submit takes {force:true} to accept warnings |
| POST | /r/{model}/{name}/actions/{action} | runs the hook; queued if queue: → 202 {job_id} |
| GET | /dashboards/{name}?period=30 | {name,label,period,widgets:[{name,type,label,span, …computed}]}; computed shape = prototype computeWidget() (number: value,rupiah,count,prev,trend,delta; chart: data[{key,label,value,count,color}],rupiah; list: rows,total) |
| GET | /events | SSE. event: record `{model,name,op:created |
| GET/POST | /changesets | list / propose (body = changeset.json without computed fields) → 201 with layers, risk, status: proposed. An op may carry base (SHA-256 hex of the file text it was computed from): propose, validate, preview and apply answer 409 stale_base when the file has changed since |
| GET | /changesets/{id} | full change set incl. history |
Ubah mode, meta.changesets and the read-only live preview (/preview…) | see contract 0015 (docs/contracts/0015-ubah-mode-and-live-preview.md) | |
| POST | /changesets/{id}/{validate,preview,approve,reject,apply,revert} | validate → validated/invalid; preview → dry run on a copy, preview:{migrations,affected,reversible}; approve needs a human session with an approver role (config.ai.approvers or owner); apply only after approve (or auto_apply: low_risk and risk low); revert re-applies the previous file versions |
| GET | /processes · /processes/{name} | process canvas graph (contract 0014 §4); only stages the caller may read; unknown or fully hidden → 404 |
| POST | /processes/{name}/ops | {edits:[{node,key,value}]} → {title,ops}, compute only (400 bad_edit); the client proposes the ops as a change set |
| PUT | /processes/{name}/layout | {groups,nodes} → stored in site/canvas/<name>.json; owner only, 400 bad_layout |
| GET | /system/status | for Console: {version,uptime_s,site,capabilities:{db:{driver,ok,latency_ms},cache:{driver,ok,hits,misses,keys},queue:{driver,ok,counts:{available,running,retryable,completed,discarded}},scheduler:{driver,ok,schedules:[{name,source,cron,next_run,last_run,last_status}]},realtime:{driver,transports,connections},files:{driver,ok},search:{driver,ok},notify:{email:{driver},push:{…},whatsapp:{…}},auth:{issuer,clients:[id]}},apps:[{name,version,models,dashboards}],orgs:n,members:n} |
| GET | /system/jobs?state= | queue jobs |
| POST | /system/jobs/{id}/replay | queue a dead-lettered job again (contract 0002 §A.5); owner or connector_auth role; 409 job_not_dead |
| GET | /system/audit?limit=50 | {data:[{at,actor,kind,target,summary}]} |
| GET | /orgs, /orgs/{id}/members | organisations and members |
| GET | /files/meta/{path} | raw .rk text + parsed JSON (Console, AI) |
Auth: POST /auth/login {email,password} → rk_session cookie; POST /auth/logout; GET /auth/me; POST /api/v1/tokens → rk_… bearer token. Rangka ID OIDC provider: /.well-known/openid-configuration, /oauth/authorize (code + PKCE S256), /oauth/token, /oauth/userinfo, /oauth/jwks (RS256). Clients come from system.rk auth.clients. Seed user: ceo@saga.co.id / rangka-demo (owner of org kopi-senja).
MCP (POST /mcp, JSON-RPC 2.0, Streamable HTTP, bearer token)
Tools (names fixed): rangka_meta, rangka_get_file {path}, rangka_query {model, filter?, sort?, limit?}, rangka_get_record {model, name}, rangka_dashboard {name, period?}, rangka_system_status, rangka_changeset_propose {title, reason, ops}, rangka_changeset_validate {id}, rangka_changeset_preview {id}, rangka_changeset_status {id}. No approve/apply tools: a person approves in Console or the app.
Change set paths
apps/<app>/{app,models/<m>,dashboards/<d>,flows/<f>,roles/<r>}.rk → files under the apps dir; system.rk, features.rk, config.rk, themes/<t>.rk, layouts/<l>.rk → files under the site dir; connectors/<c>.rk → connectors dir. Risk: high when touching system.rk, roles/permissions, a currency/stock field, a submittable model's existing fields, or deleting anything; medium for new fields/rules on existing models; low for themes, layouts, labels, dashboards.
Kernel v0 additions (30 Oct 2026, rangka-os/kernel)
Additive; nothing above changed. Clients may rely on these.
- Errors other than 422 are
{error:{code,message}}. 422 issues are{field?, rule?, code, message}with codesrequired,min_rows,rule,link_not_found,bad_option,bad_value,unique. Successful writes may carry_warnings:[…](save rules withlevel: warn). POST …/submitwith warnings and noforce→ 422{errors:[], warnings:[…], needs_force:true}.- (Nov 2026)
POST /r/{model}/submit {names:[…], force}submits up to 100 drafts of one model, each on its own asPOST /r/{model}/{name}/submitwould (rules, approvals, numbering, hooks, flows). 200{results:[{name, status, new_name? | approval? | error?, warnings?}], submitted, held, failed}in the order given (duplicates once):status200 submitted, 202 held (the pending request), or the single submit's error status with itserror. One refused draft does not stop the others. A retry is safe andIdempotency-Keyis not used here: a submitted draft has its number, so its draft name answers 404not_found(the number 409not_draft), and a held draft reuses its pending request. - (Nov 2026)
read_onlyfields, also on child rows, are ignored in client writes;min_rowsis checked on a client create (and on a PATCH that sends the table) as well as on submit; date-dependent computes are recomputed on read. See kernel/README.md. - Submittable records carry a derived
status;/metamodels getappand, for those,status_field: true./metaalso returnsinstalled,org,user,today,config(locale, currency, timezone, tax, plan, theme, layout) andcapabilities(from the site's plan). - Extra endpoints:
GET /files/meta(list of paths),GET /system/jobs/{id},GET /system/audit?kind=<prefix>,POST /flows/{name}/run {event:{…}}(run a flow now, e.g. a connector event).GET /dashboards/{name}setsX-Cache: hit|miss; widget objects keep their definition keys (chart, aggregate, columns, span …) next to the computed ones. - Change sets: validation items are validator items
{level,file,pos,path,code,message}withfileas a change-set path;previewmay addnotes(schema drift). Approve, reject and revert need a browser session (not a token) with an approver role; applying an approved change set needs an approver (session or token). MCP proposals default to author kindai, API tokens tocli, sessions touser. - OIDC access tokens are accepted on
/api; on/mcpthey need therangka.mcpscope. API tokens (rk_…) work on both.
v0.1 decisions (30 Oct 2026, after the first build round)
Settles the questions raised by kernel, Console and rangka-ai. Binding for the reconciliation round.
- Installed apps are explicit.
config.rkgetsapps: [core, crm, sales](schema: array of app names). The plan infeatures.rklimits what may be listed; the kernel refuses an app the plan doesn't allow./meta.installed= config.apps. - Company layer = overlay files, never edits to app files. Fields, rules and view tweaks an organisation adds live in
<site>/custom/<model>.rk(kindoverlay, new schemaoverlay.json):model: sales_invoice,fields: [...](names must start withx_),rules: [...],views: {form: {add: [{field, after}]}, list: {add: [...]}}. The kernel merges overlays onto the app model at load; app upgrades never touch them. Change-set pathcustom/<model>.rk. Rangka AI writes new fields/rules here, not inapps/. Editingapps/**is for app authors (risk high unless the file is new). - Field flags for risk. Field properties
money: true(currency fields are money by default) andstock: true(quantity fields that move stock). Risk: high for changes touching money/stock fields,system.rk, roles/permissions,config.tax, deletions, existing fields of submittable models; medium forfeatures.rk, flows, new fields/rules/overlays,config.apps; low for themes, layouts, labels, dashboards. - Approval. Approve only from
previewed. High-risk approval only by anowner(kernel returns 403owner_required); medium/low by any role inconfig.ai.approvers(default[owner]). - /meta adds:
flows,roles,connectors(installed, with triggers/actions/secret field names),site:{config, features, themes:[names], layouts:[names], system:{parsed, secrets redacted}}. Every model, dashboard and flow carriesapp.GET /api/v1/files→[{path, kind, layer, app?, lines, sha}](replaces/files/metalist; keep the old one as alias).GET /api/v1/files/{path}→{path, kind, layer, text, parsed}. - /system/status adds:
deploy:{target: dev|docker|helm|desktop|cloud|partner, started_at},schema_version,connectors:[{name, ok, events_24h, calls_24h, errors_24h, last_event_at}], andauth.clientsas[{id,label,redirect_uris,scopes,public}]. - Change sets add
created_at,updated_at, andpreview.files:[{path, before, after}](full text, for diffs). - Shapes. job
{id, kind, queue, state, attempt, max_attempts, created_at, scheduled_at, finished_at, error, args, org}; member{id, email, name, roles[], two_factor, status, last_seen_at}; org{id, name, plan, usage:{users, outlets, records, storage_mb, ai_credits_month}}; audit entry{at, actor, kind, target, summary, org}with?kind=&actor=&org=. - MCP results. Every tool returns
content:[{type:"text", text:<json>}]plusstructuredContent:<json>; errors areisError:truewith{error:{code,message}}.rangka_get_file→ theGET /files/{path}shape;rangka_meta→/meta. - System columns. The record creator is
created_by(notowner), so models may define their ownowner/statusfields. Derivedstatusexists only for submittable models without their ownstatusfield. - Schemas to add:
overlay.json,role.json,connector.json,template.json; flowstepstyped (find,find_all,create,update,notify,call(connector action),if,wait). - Theme dark derivation. A colour given only as a string gets its dark value by: keep hue, lightness → 100 − L·0.6 for backgrounds/tints (
selected,*-tint), and +15 lightness for foregrounds/accents (primary,brand,chart-*,selected-ink,link), then enforce the contrast floors. Both Console and kernel use this rule. - Drop the unnamed
theme.rk/layout.rkchange-set paths; usethemes/<t>.rk,layouts/<l>.rk. - Reference validator (
rangka-os/tools/rangka_validate.py) must also schema-check every kind, check site files (config.apps vs plan, theme/layout names exist, theme contrast), overlays, treatinas an operator, and report cycles deterministically. The Go validator keeps byte-identical output.
v0.1 implementation notes (30 Oct 2026, kernel + reference validator)
How the kernel and rangka_validate.py implement the v0.1 decisions where the decision left details open. Additive; nothing above changed.
- Validator CLI:
rangka_validate.py <apps> [--site <dir>] [--connectors <dir>] [app …](Go:rangka validatewith the same flags; output byte-identical). New codes:never_runs(warn),unknown_event,unknown_connector,unknown_trigger,unknown_action,unknown_app,unknown_plan,app_not_in_plan,missing_dependency,unknown_theme,unknown_layout,not_installed(warn),unknown_template(warn),low_contrast,optional_model(layout nav),unknown_widget; overlays reuseunknown_model,unknown_field,duplicate_field,name_mismatch,compute_cycle.SYSTEM_FIELDSnow hascreated_byinstead ofowner. - Overlays:
x_fields are stored in the record'sxJSONB column (no DDL). Merge order: app fields, then overlay fields; rules appended;views.form.addinserts afterafterin the section or column that holds it (else at the end of the last section);views.list.addlikewise in the columns. Overlays are layer 4. Records of a model whose overlay is removed keep theirx_values. - Dark derivation (decision 12): colorsys HLS;
selectedand*-tint→ L' = 100 − L·0.6, every other token → L + 15 (max 100). Floors are enforced against the dark partner in 1 % lightness steps (foreground up, background down). Pairs and floors:ink,ink-2,muted,linkonsurface,selected-inkonselected,primary-inkonprimary,ok|warn|bad|info|discoveryon their-tint: 4.5:1;primary,brand,focus,chart-1…6onsurface: 3:1.low_contrastis reported only for pairs that involve a token the theme overrides (contrast_check: falseskips it)./meta.themeaddsoverrides: {token: {light, dark, dark_derived}}. - Risk details: editing an existing
apps/**file is high; a new app file is low (dashboard), medium (model, flow, app) or high (role, or a new model with money/stock fields).config.rk:taxandaihigh;theme,layout,localelow; anything else medium. Overlays: new → medium; money/stock fields, removed fields and changed fields of submittable models → high; views only → low. - Approval: validate → preview → approve. Approve, reject, revert need a browser session; high risk needs
owner(403owner_required); otherwise a role inconfig.ai.approvers(owner always). Apply of an approved change set: any approver (session or token).preview.filesholds{path, before, after}withnullfor an absent file. - Lists:
GET /files,/system/jobs,/system/audit,/orgs,/orgs/{id}/membersanswer{data:[…]}. Audit?org=must be an org the caller belongs to (else 403). Memberroleshas one role per org in v0;two_factoris false until 2FA ships. Orgusage.storage_mbis 0 until file uploads ship;ai_credits_monthcounts AI-authored change sets this month. - Connectors: installed = referenced by an installed flow (
on:orcall:) or bysystem.rk notify.*.connector. Health counts audit entriesconnector.event/connector.call/connector.errorwith targetconnector/<name>.call:steps queue acalljob that renders the request at send time and sends it (contract 0002 §A, 0017 §5–§8); webhooks arrive at/hooks/<org>/<connector>/<trigger>. - Flows:
update: <variable>needs a record found or created earlier;if:+then:/else:branches;wait:only at the top level (a duration, or{until: cel}re-checked every minute) queues the rest as aflowjob.POST /flows/{name}/run {event}runs a flow now (recordsconnector.eventfor connector-triggered flows). - Automations:
when:is<field> changes to <CEL value>,<field> changes, orcreated|updated|submitted|cancelled;if:is evaluated on the record;do:names a hook, run in the same transaction (auditautomation.run). Built-in hooks:crm.convert_lead,crm.mark_won(won deal → draft sales invoice for its customer and the first outlet, once). - MCP errors:
{error:{code,message}}pluserrors/warningsfor validation failures anddetailfor change-set errors;structuredContentis set on errors too.