MODULE GUIDE — building a StrataBI module: Python Lambdas, OpenTofu, pages, HTML blocks, AWS
(schema 1.13; for anyone building or changing a module. Dashboards and pages: the DESIGN GUIDE.)

0. FIRST: does it need a module at all?
  - A dashboard built from Athena SQL, cached results and the installed modules' Lambdas needs no
    new module. Read the installed modules' manuals (llm_context) before writing one: if a function
    already computes it, call it from a tile.
  - Build a module when you need code: a model, an API call, a write-back, a multi-step job, a
    reusable visualization (an HTML block), or pages that belong together as an app.

1. ANATOMY (strataforge new module <id> scaffolds it; every file below is checked by strataforge validate)
    module.json             the manifest: module_id, module_type (below), label, version,
                            lambdas[] {function_id, handler, runtime, memory_mb, timeout_seconds,
                            trigger}, pages[] {page_id, label, layout[]}
    pages/<page>.json       a page = an ordinary dashboard layout (the DESIGN GUIDE applies)
    src/<function_id>/      handler.py (+ requirements.txt): one Lambda per function_id
    terraform/              main.tf, variables.tf: deploys the Lambdas, registers the module
    llm_context.txt         the module's manual for AI and people (section 7)
    stratabi-module.json    the bundle manifest stratactl reads: module_id, version, entrypoint
                            "tofu", state_key, supports_destroy, required_permissions
    blocks/<block>/         optional external HTML blocks (section 5)
  module_id: lowercase, [a-z0-9_]. Tiles call a function with
    "exec": {"type": "lambda", "module_id": "<id>", "lambda_index": <index in lambdas[]>}
  module_type says what StrataBI does with it (module schema 1.6.0):
    app                      a one-page application StrataBI renders from its top-level layout[]
    multi_page_app           an application StrataBI renders from pages[] (Apps catalog)
    html_app                 an embedded application with its own HTML front end (section 5b)
    single_lambda | microservices   Lambdas that tiles call (exec.type lambda)
    standalone_service       runs beside StrataBI with its own UI or API (a Fargate / ECS service, an
                             API Gateway endpoint); StrataBI never renders it or offers it to tiles;
                             entry_url ("/forge/" or https://…) is where its Apps entry opens. No pages.
    background_service       Lambdas or workers with no StrataBI surface (scheduled, stream- or
                             event-driven); never rendered, never callable by tiles. No pages.

2. THE TILE LAMBDA CONTRACT (Python)
  Core invokes the function with an event:
    inputs            every dashboard input, by input_id ({"region": "West", "horizon": 6}); may be {}
    tile, tile_id     the calling tile's JSON (its config, query, title)
    run_id            unique per run; make work idempotent on it
    actor, actor_verified, auth_mode   who asked (trust actor only when actor_verified is true)
    status_context    where the result goes: system_bucket, result_s3_key, result_kind
                      (dataframe | artifact), result_format (parquet | csv | md | json | html),
                      run_id, tile_id, dashboard_key…
    status_writer_lambda_arn   set for async runs (the default): report there when done
    invocation        "sync" (exec.sync: true, answer within exec.timeout_seconds) or async
  Write the result to s3://<system_bucket>/<result_s3_key>, then report:
    async: invoke the status writer (InvocationType "Event") with {**status_context,
           "status": "SUCCEEDED" | "FAILED", "message": "..."}; return the same dict.
    sync:  return {"status": "SUCCEEDED", "message": "ok"} (or raise; core shows the error).
  Results: a dataframe as Parquet (pandas/pyarrow: df.to_parquet(buf, index=False)), Markdown
  as text/markdown, JSON for a raw_html/external block. Column names are what tiles bind
  ("@revenue", template "{revenue:,.0f}") — name them deliberately and keep them stable.
  Handler shape:
    _s3 = boto3.client("s3")                    # clients at module scope (reused across calls)
    def build(inputs, ctx) -> DataFrame | str:  # pure logic, unit-testable
    def handler(event, context=None):           # thin: read status_context, build, write, report
  Good practice: validate inputs (types, allowed values) before using them; never put input values
  into SQL by string concatenation (Athena: ExecutionParameters, or a validated allow-list);
  log run_id and timings, never secrets, tokens or row data; stay under the timeout (long work →
  async, Step Functions, or a queue); deterministic column order and types (cast explicitly);
  pandas/pyarrow from the AWS SDK for pandas Lambda layer rather than a 200 MB zip; arm64 is
  cheaper and usually faster.

3. OPENTOFU / HCL (terraform/)
  - Every name derives from the module id and the installation prefix:
      "${var.name_prefix}-${local.module_id}-${each.key}"   — never a literal name. This is what
    lets the same code deploy as a Facies or a sandbox (a renamed, isolated copy).
  - terraform { backend "s3" {} } with nothing inside: the installer (stratactl, a sandbox job or
    your pipeline) supplies bucket, key and lock table. Never commit state or tfvars.
  - No hard-coded account, region or bucket: data "aws_caller_identity" / "aws_region", and
    variables whose blank default derives the value (scaffold: system bucket, registry table).
  - for_each over the manifest's lambdas (local.functions = {for f in manifest.lambdas : …}),
    archive_file per function, source_code_hash so a code change redeploys.
  - IAM: one role per function, least privilege — s3:PutObject on the result prefix,
    lambda:InvokeFunction on the status writer, plus exactly the data it reads (a table, a prefix,
    an Athena workgroup). Every role carries the sandbox boundary when one is given:
      variable "permissions_boundary" { type = string, default = null }
      resource "aws_iam_role" "fn" { … permissions_boundary = var.permissions_boundary }
    (a sandbox's IAM refuses roles without it).
  - aws_cloudwatch_log_group "/aws/lambda/<function name>" with retention_in_days (30), declared
    before the function, so logs are not kept forever.
  - Registration: upload module.json and llm_context.txt to <system bucket>/analyst/modules/<id>/
    and write one row to the module registry table (aws_dynamodb_table_item) — exactly what the
    scaffold does. Sandboxes also pass sandbox_owner / sandbox_expires_at: put them on the row
    ("sandbox": {owner, expires_at}) so StrataBI shows the sandbox to its owner only.
  - Outputs: function names/ARNs. Mark anything secret sensitive = true (the runner masks them).
  - tofu fmt and tofu validate pass; strataforge facies check finds no shared names.

4. PAGES (multi_page_app)
  - Each page's layout is a dashboard: follow the DESIGN GUIDE (rails, compact control groups,
    KPI cards, formatted tables). Tiles call this module's own functions by lambda_index.
  - strataforge preview module.json --page <page_id> shows a page before anything is installed
    (its tiles call the INSTALLED module, or the module's sandbox once deployed).

5. EXTERNAL HTML BLOCKS (JS / HTML) — blocks/<block>/
    block.json   {"contract": 1, "block": "<name>", "version": "1.0.0", "name": "Time series",
                  "entry": "renderer.html", "assets": ["assets/lib.js", …],
                  "schema": "options.schema.json", "example": {"options": {…}}}
    renderer.html + assets/  plain HTML/JS/CSS, no build step; vendored libraries with their
                  licenses in licenses/
  The block runs in a sandboxed frame (scripts only: no same-origin, no network, no forms, no
  popups). Everything it gets is on window.StrataBlock:
    options (the tile's config.options), data ({"columns": [...], "rows": [[...]]} for a dataframe
    result), theme ({colors, font, mode}; CSS variables --sb-<color>, --sb-font are set),
    assets (data: URIs of the listed assets), fail(message), onResize(fn(width, height)).
  Draw responsively (fill the frame, redraw onResize), use the theme's colors, call fail() with
  a clear message for bad options or empty data. A tile uses it:
    "block": {"type": "raw_html", "config": {"extension": {"module_id": "<id>", "block": "<name>",
              "version": "1.0.0"}, "options": {…}}}
  Preview a block before installing it: strataforge preview blocks/<block>/ [--in <dashboard.json>].
  A block that filters the page (a chart people click) may opt in to the page's inputs with
  "bridge": ["params"] in block.json: StrataBlock.setParam(name, value) and onParam(name, fn) then
  set and read the page's inputs, and native tiles re-run through triggered_by. Nothing else: a block
  never calls a Lambda.

5b. EMBEDDED APPS (module_type html_app) — when it is an application, not a view
    module.json  "module_type": "html_app", no pages, and
                 "app": {"entry": "app/index.html",
                         "operations": [{"op": "state", "function_id": "ui_handler", "mode": "sync"},
                                        {"op": "run", "function_id": "api", "mode": "async",
                                         "input_schema": {"type": "object", "required": ["sql"]}}],
                         "open_external_hosts": ["*.studio.sagemaker.aws"]}
    blocks/app/  the front end, packaged like a block (section 5) with "kind": "app" in block.json and
                 the entry app.entry names ("index.html"); scripts and styles bundled, nothing fetched.
  StrataBI shows it as one tile filling /dashboard/apps/<id>, or on any dashboard as
  {"type": "html_app", "config": {"module_id": "<id>", "params": ["run"]}}. To put native tiles beside
  the app on its own page (a results table that re-runs on the app's "run" param), give "app" a "layout":
  a dashboard layout with the app tile in it ({"type": "html_app", "config": {"params": ["run"]}}; the
  module_id defaults to this module) and the tiles that list "run" in triggered_by. The frame has a null
  origin and no network; window.StrataApp is its only way out:
    call(op, args)            sync: the op's JSON result; async: a handle {op, run, status}
    watch(handle, onUpdate?)  the async run's result once it SUCCEEDED (rejects when it FAILED);
                              onUpdate sees each state, with the module's progress message while it
                              runs. A JSON result resolves to the value; a file written with its own
                              Content-Type (text/csv, text/markdown, ...) to {format, name, bytes, text?}
    setParam(name, value) / onParam(name, fn)   the page's inputs (and the tile's own config.params)
    download(handle, filename?)  the run's artifact (needs the download permission)
    navigate("/dashboard/...") StrataBI paths only · openExternal(url) https, open_external_hosts only
    theme(fn?) · copy(text) · resize(px?)
  Each call is an ordinary tile run of the op's function, as the person viewing it: the usual tile event
  (status_context with actor and actor_verified; the identity assertion when the handoff is on) plus
  "app": {"op": "<op>", "args": {...}}; event.tile.id is the app tile's id. Dispatch on app.op, write the
  JSON result to status_context.result_s3_key (result_format json), return {"status": "SUCCEEDED"}; an
  async op reports through the status writer as an async tile does (its message is what watch shows
  while the run goes on). A sync result is JSON, at most 1 MB; keys keep the order you wrote them in.
  args are a JSON object checked against input_schema before your Lambda runs; still check what you
  act on. StrataBI refuses a call without sign-in, from another site, with a tile it did not issue, for a
  viewer without access to the module, for an op app.operations does not list, with invalid args, or
  over the size and rate limits. There is no route per module and no call to another module's ops.

6. AWS PRACTICE (the account is the customer's; leave it as you would want to find it)
  - Athena: Parquet, partitioned by date (partition projection), queries that filter on partition
    columns, the deployment's workgroup; results to the workgroup location, not a new bucket.
  - S3: one prefix per module under the existing buckets; SSE (S3-managed or the deployment's KMS
    key); no public access; lifecycle rules for scratch data.
  - DynamoDB: on-demand billing, a partition key that spreads load, TTL for transient rows.
  - Long or multi-step work: Step Functions or SQS + a worker, not a 15-minute Lambda; schedules
    with EventBridge Scheduler.
  - Secrets: Secrets Manager or SSM SecureString, read at runtime by ARN; never in code, tfvars,
    environment variables in plain text, or logs.
  - Cost: Lambda memory sized by measurement; Athena bills bytes scanned (select only the columns
    needed); nothing left running that a tile does not need.
  - Tags on everything: module_id, version (default_tags in the provider).

7. llm_context.txt — the manual other people's AI reads to REUSE your module (write it well)
    # <id> — <label> (installed StrataBI module, v<version>)
    - summary: what it computes, from what data, how fresh
    ## Functions
    - lambda_index 0 (<function_id>)
      reads inputs:  <input_id> (type, allowed values, default)
      returns:       dataframe — <column> (<type>, meaning), … (or markdown / json)
      suits:         plotly (line …), table, markdown template
      cost / speed:  ~N s; async
    ## Reference from a tile
    {a complete, working tile JSON calling it}
  Keep it short, exact and current: column names, types and input ids are the contract.

8. THE LOOP (in StrataForge)
    strataforge validate <project>  →  strataforge lint (its pages)  →  strataforge package  →
    strataforge sandbox deploy <project> (StrataCI's sandbox pipeline; torn down at expiry)  →
    preview the pages, look and drive (view_observe / view_set_input)  →  fix  →  redeploy  →
    strataforge sandbox destroy  →  facies / handoff for a permanent install by an operator.
  Never deploy around the pipeline: no tofu apply from a workspace, no AWS console changes.
