# AGENTS.md Rules for developing Classic ASP applications that run on **AxonASP** (Go-based Classic ASP / VBScript 5.8 runtime, https://github.com/guimaraeslucas/axonasp). Sources: the AxonASP manual (in the container at `/opt/axonasp/www/manual/md`, notably `authoring/llm-classic-asp-coding.md`, `asp/*`, `asp-modernization/*`, `runtime/*`, `config/*`, `libraries/*`) plus problems verified while porting this project. Items marked **[verified here]** were reproduced in this repo's container; the rest come from the manual. When unsure about an object, ProgID, method or config key, check `/opt/axonasp/www/manual/md` in the container before guessing. Do not invent APIs. --- ## 1. Project layout and how to run it ``` (repo root) the application (MVC starter, "RouteKit"), also the git repo root public/ web root (Default.asp front controller + routes, web.config, api/*.openapi.json specs) core/ framework code (autoload_core.asp, mvc.asp, lib.*.asp incl. lib.JsonLite.asp, helpers.asp) app/ controllers/ (HTML: Controller, JSON: ApiController), models/ (POBO_, Repository), views// db/ app.sqlite (SQLite, git-ignored) and migrations/ scripts/ migrate.cmd/.asp, gen.cmd (generators: migration, repo, controller, api), templates/ (POBO, Repository, Api). Run through the AxonASP CLI in the container. docker-compose.yml the AxonASP container (stock image ghcr.io/guimaraeslucas/axonasp) api-tests/ created by `gen.cmd api`: .http sample requests (VS Code REST Client) ``` - Run: `docker compose up -d` from the repo root -> http://localhost:8801 - Compose mounts the whole repo at `/opt/axonasp/site` and sets `SERVER_WEB_ROOT=/opt/axonasp/site/public`. This keeps `../core`, `../app`, `../db` reachable from `public/`, and is the layout `gen.cmd` / `migrate.cmd` expect (container name must be `axonasp`). - Migrations: `scripts\migrate.cmd status|up|down` (runs `axonasp-cli` inside the container). - Swagger UI for the JSON APIs: http://localhost:8801/api/docs (needs internet: loads Swagger UI from the jsDelivr CDN). - The AxonASP manual is inside the container: `docker exec axonasp ls /opt/axonasp/www/manual/md` (libraries/, asp/, runtime/, ...). There is no `deploy/` folder in this repo. ### Memory API (Phase 1) workflow - Provision with `scripts\provision.cmd` (tenant, principal -> API key printed once, namespace, grant, revoke, list, purge). API calls use `Authorization: Bearer `; the tenant comes from the key. - Controllers `ApiMemoriesController`, `ApiSessionsController`, `ApiHealthController` are hand-written (the generators cover one-table CRUD only); routes under `/api/v1/...` are in `public/Default.asp`. - Regression suite: `bash tests/phase1-api.sh` (needs the container running; creates and purges its own tenants; ends with a container restart). - Phase 2 (documents): `ApiDocumentsController` (ingestion/jobs, jobs, documents, chunks, search) plus `POST /recall` and `POST /memories/:id/verifications` in `ApiMemoriesController`; chunker and FTS5 indexing live in `core/lib.Search.asp`. Regression suite: `bash tests/phase2-api.sh`. OpenAPI: `public/api/memory-v1.openapi.json`. A caller without the needed namespace permission gets 404, never 403. - Phase 3 (context): `ApiContextController` (`POST /context`) assembles a budgeted briefing. Constraints are loaded by scope (not similarity) and are required: if they do not fit `max_context_tokens` the answer is 422 `context_budget_exceeded`. Regression suite: `bash tests/phase3-context.sh`. - Semantic retrieval: `core/lib.Embeddings.asp` (Ollama client, Qdrant client, `embedding_index` bookkeeping, `Ranker_Class` used by recall/search/context). Write paths call `Emb_MarkPending`/`Emb_MarkDelete*` inside their transaction and `Emb_AfterWrite` after commit; new write paths that change memory or chunk text must do the same. `scripts\embed.cmd status|run|reindex`. Regression suite: `bash tests/phase3-semantic.sh`. The `embed-worker` container runs `scripts/embed.asp` (`EMBED_ACTION=worker`) every 30 seconds to retry pending/failed items. - Learning loop: `ApiLearningController` (session events, `POST /learn`, candidates, review, `GET /memories/:id/sources`, `POST /feedback`) with helpers in `core/lib.Learning.asp`: `Evidence_Class` (validate, resolve and pin evidence), `Mem_Create`/`Mem_Revise`/`Mem_Verify` (memory writes shared with review; inside a transaction), `Mem_ForgetLinked` (called by forget), and `Tel_*` (retrieval telemetry: recall/search/context must record the `query_id` they return and the revision of each result, or feedback cannot reference them). Review needs `verify` and is refused to the author without `admin`. New tenant-scoped tables must also be deleted by `provision purge`. Regression suite: `bash tests/phase3-learning.sh`. - The AxonASP image is pinned by digest in `docker-compose.yml`. To upgrade, change the digest deliberately, `docker compose up -d`, and rerun all five suites (`tests/phase*.sh`). ### This repo's own knowledge base (dogfooding) The running API holds a tenant for this repo (`agent-memory-dev`, namespace `/projects/agent-memory`). Settings and keys are in `.amk.env` (git-ignored, local only; never print or commit the keys). Use `bash scripts/kb.sh` from Git Bash: - At the start of a task: `kb.sh context ""` (verified lessons/decisions plus passages from the ingested docs), or `kb.sh search ""` for a quick lookup before reading whole files. - After learning something non-obvious (a new gotcha, a decision): `kb.sh learn lesson|decision|constraint "" "<content>"`. It stays a proposal until the owner reviews it (`kb.sh candidates`, `kb.sh review <id> accept|reject`); the agent key cannot approve its own proposals, and agents must not use `AMK_OWNER_KEY`. - After editing AGENTS.md, README.md or the specification: `kb.sh ingest <file>` (re-ingesting replaces the previous revision). - The tests never touch this tenant; `provision purge` on it deletes everything. ### Adding a table end to end (the workflow that was verified) 1. `scripts\gen.cmd migration create_<table>_table`, then fill in `Migration_Up`/`Migration_Down` by hand (the generator leaves TODOs), then `scripts\migrate.cmd up`. 2. JSON API: `scripts\gen.cmd api /table:<Table> /pk:Id`. One run writes the POBO + repository, `Api<Table>Controller.asp`, the includes, the controller whitelist entry, six routes under `/api/<table>`, `public/api/<table>.openapi.json` (shows up in the `/api/docs` dropdown) and `api-tests/<table>.http`. Validation comes from column types and NOT NULL/DEFAULT, `CreatedAt`/`UpdatedAt` text/date columns are set by the server, and an existing controller is never overwritten. Business rules (ranges, formats) are added by hand. 3. HTML pages: `scripts\gen.cmd controller <Name> Index "Show(id)" NewForm Create "Edit(id)" "Update(id)" "Delete(id)"` writes a stub controller and wires it (include, whitelist, routes: Index/NewForm/Create/Show/Edit/Update/Delete get REST routes, any other action gets `GET /<name>/<action>/:param`). The actions and `app/views/<Name>/{index,show,form}.asp` are filled in by hand. Pattern used by the (removed) sample CRUD: list with `?q=` search and `?page=` paging via the repository's `SearchTablePaged`; forms carry `HTMLSecurity().GetAntiCSRFToken(name)` as a hidden `csrf_token` and POST actions check `IsValidAntiCSRFToken` (failure: flash error + redirect); validation errors re-render the form with status 422; deletes are POSTs; all output goes through `Server.HTMLEncode`; the layout header is already buffered, so `Response.Clear` before `Response.Redirect`. Put `Const` values outside the class (section 8). 4. `docker restart axonasp`, then test (section 10). Add a nav link in `app/views/shared/header.asp` for new HTML pages. - Run `gen.cmd controller` from PowerShell or cmd, **not Git Bash** (quotes such as `"Show(id)"` reach the script literally; the generator strips them now, but cmd quoting is still the reliable path). Generators run inside the container with the framework folder as web root, so they use paths like `/public/...`, `/app/...`. --- ## 2. Language rules (strict Classic ASP / VBScript 5.8) 1. `Option Explicit` in every page and include that owns top-level code. 2. **Never single-line `If`.** Always `If ... Then` / `End If`. 3. Declare and assign separately. No `Dim x = 1`. No `As Type` unless deliberately using an AxonASP extension (section 4). 4. `Set` for every object assignment. Release long-lived objects with `Set obj = Nothing`. 5. Calling a Sub or method with no return value: no parentheses, or `Call name(args)`. `Foo(a, b)` as a statement is wrong. Calling a Function and using its result: parentheses required. 6. **No short-circuit `And`/`Or`.** Both sides are always evaluated, so `If Not rs.EOF And rs("x") = 1` and `If s = "" Or CDbl(s) > 1` both fail. Nest the `If`s. (`AndAlso`/`OrElse` are AxonASP extensions; see section 4.) 7. Concatenate with `&`, never `+`. 8. `=` is both assignment and comparison. String `=` comparison is case-insensitive. 9. Line continuation is ` _` at end of line. Statements do not wrap otherwise. 10. Error handling: `On Error Resume Next`, check `Err.Number`, then `Err.Clear` / `On Error GoTo 0`. Keep the scope of `Resume Next` small and check errors right after the risky statement. Never use it to hide failures: report the error (number, description, and the SQL or input involved). 11. Directives: `<%@Language="VBSCRIPT" CodePage="65001"%>` on the very first line, compact, one line. Never leave `<%` or `%>` unclosed. 12. Procedure arguments are **ByRef by default**. Use `ByVal` when the caller's variable must not change. 13. Names are case-insensitive. Do not let a local variable or parameter share a name with a class member or a Sub/Function (see gotchas). 14. Always HTML-encode output: `Server.HTMLEncode(value)`. Always URL-encode query values: `Server.URLEncode`. 15. `Application` writes must be wrapped in `Application.Lock` / `Application.Unlock`. Never `Response.Redirect` or `Response.End` while locked. 16. Do not store large objects in `Application`/`Session`. --- ## 3. Includes, paths and files - `<!--#include ... -->` is textual and resolved **before** execution. The path cannot be a variable. - The manual says `file=` is relative to the including file and must not use `..`; `virtual=` is relative to the web root and is the preferred form. This project's framework uses `file="../core/..."` and it works on this build **[verified here]**, but prefer `virtual=` for anything under the web root, and keep includes that cross out of `public/` consistent. - **Linux is case-sensitive.** Include paths must match the real file name case exactly (`../core/` not `../Core/`, `lib.Collections.asp` not `lib.collections.asp`). Check this whenever you add or move a file. - Includes inside a `Sub` are allowed here (the MVC dispatcher does it) but inject the file text at that spot. - `Server.MapPath("/x")` is relative to the web root. A relative path is relative to the current script's directory. Under the CLI the web root and script directory can differ from the web server; see section 8. - `Scripting.FileSystemObject` is limited to the web root unless `server.allow_external_filesystem_access = true` in `axonasp.toml`. Keep new file access inside the web root (or the mounted framework folder when running the CLI with that as root). - `global.asa` lives at the web root. It is compiled at startup; restart to pick up changes. Request/Response are not available in Application events. --- ## 4. AxonASP extensions (use deliberately, and only in new code) AxonASP adds VB6/VB.NET-style features. They make code non-portable to IIS, so use them only when the project has chosen AxonASP permanently, and note it in a comment. - Short-circuit `AndAlso`, `OrElse`; `IsNot`; `<<` / `>>`. - `On Error GoTo <label>`, `GoTo`, `Resume`, `On Error GoTo -1` (classic VBScript only has `Resume Next` and `GoTo 0`). - `Optional` / `ParamArray` parameters, `Static`, `Enum`, `Type ... End Type` (UDT), `Dim x As Type`, `Implements`, `Event` / `RaiseEvent` / `WithEvents`, non-zero array bounds and `Option Base`. - `console.log/info/warn/error` for diagnostics. - Native VB6 file I/O statements work **only in the CLI**, not the HTTP server. - The built-in `Collection` object and `[DispId(-4)]` for-each delegation. The portable rules in section 2 remain the default for framework and application code. --- ## 5. Objects and libraries Create objects with `Server.CreateObject("ProgID")` using exact ProgIDs from `/opt/axonasp/www/manual/md/libraries/overview.md` (in the container). Names are case-insensitive. AxonASP maps ProgIDs to native Go implementations; it does not use the Windows registry or COM. - **Prefer native libraries over hand-rolled ASP:** `G3JSON`, `G3DB`, `G3HTTP`, `G3CRYPTO`, `G3MAIL`, `G3FILES`, `G3TEMPLATE`, `G3MD`, `G3IMAGE`, `G3PDF`, `G3ZIP`, `G3FILEUPLOADER`, `G3STRINGBUILDER`, `G3AXON.FUNCTIONS`. **Exception:** do not use `G3JSON.Parse` in a request that also uses `G3DB` (see section 8); the API controllers use the pure-VBScript `core/lib.JsonLite.asp` instead. - `Val()` is not usable in this build (Type mismatch even for "7"). Convert with `CDbl` (mind the locale decimal separator: JSON uses `.`). - Compatibility objects exist and are fine to use: `Scripting.FileSystemObject`, `Scripting.Dictionary`, `ADODB.Connection/Recordset/Command/Stream`, `MSXML2.ServerXMLHTTP`, `MSXML2.DOMDocument` / `Microsoft.XMLDOM`, `VBScript.RegExp`, `WScript.Shell` (environment/exec only), CDO aliases for `G3MAIL`. - Already replaced by natives (do not reintroduce): JSON parsing -> `G3JSON` (outside the DB-request caveat above), file upload -> `G3FILEUPLOADER`, email -> `G3MAIL`, password hashing and GUIDs -> `G3CRYPTO` (`HashPassword`/`VerifyPassword` use bcrypt, `UUID()`). - **Do not use:** Windows Script Components (`.wsc`, `GetObject("script:...")`), the `WScript` host object, `cscript`/WSH scripts, `regsvr32` COM, Access-only SQL. - Unknown ProgIDs fall through to host-level `CreateObject` and will fail on Linux. Verify a ProgID in the manual before using it. - `Request.ServerVariables("HTTP_X_ORIGINAL_URL")` is an IIS URL Rewrite header and is empty here. Use `GetRequestPath()` from `core/helpers.asp`. ### Database - The target database is **SQLite**. Access (`.accdb`/`.mdb`, Jet/ACE) is Windows-only and is not supported in the Linux container. - The app's data layer (`core/lib.Data.asp`, `DAL()`) runs on **G3DB**. `ConnectionString` in `public/web.config` is `<driver>:<dsn>`, currently `sqlite:/opt/axonasp/site/db/app.sqlite`. Use `DAL().Query(sql, params)` (result set), `DAL().Exec(sql, params)` (returns RowsAffected/LastInsertId), `DAL().Execute`, `PagedQuery(sql, params, per_page, page)` (LIMIT/OFFSET), and `BeginTransaction/CommitTransaction/RollbackTransaction`. `params` is Empty, one value, or an array (max 8). Failures raise a VBScript error that includes the SQL. - G3DB result sets support `EOF`, `MoveNext`, `rs("col")`, `rs(0)`, `Fields.Count`, `GetRows`, `Close`. They do **not** expose column names (`Fields(i).Name` fails), so anything that needs names must select explicit, aliased columns. G3DB does not expand an array into parameters and gives no driver error text for statements inside a transaction. - `G3DB` is the preferred native API for new code: `db.Open("sqlite", path)`, `db.Query(sql, params...)`, `db.Exec(sql, params...)`, `db.Begin()`. It returns `Empty` on failure and reports via `db.LastError`. - Write SQLite-compatible SQL: no `TOP n` (use `LIMIT n`), no `#date#` literals (use ISO `'YYYY-MM-DD HH:MM:SS'` text), `INTEGER PRIMARY KEY AUTOINCREMENT`, `DROP INDEX name` (no `ON table`). `ALTER TABLE ... DROP COLUMN` needs SQLite 3.35+. - Always use `?` parameters for user input. **[verified here]** the old ADODB `Command.Execute(, Array(...))` path failed with "missing argument with index 1"; G3DB parameters work. - Run schema changes only through migrations (section 7), never by hand against `app.sqlite`. --- ## 6. Configuration - Server config: `/opt/axonasp/config/axonasp.toml` inside the container (stock image; override with env vars in `docker-compose.yml`). Any key can be overridden by an environment variable when `viper_automatic_env = true`: `[server] web_root` -> `SERVER_WEB_ROOT`, `server_port` -> `SERVER_SERVER_PORT`, `[global] default_mslcid` -> `GLOBAL_DEFAULT_MSLCID`, and so on. A different config file: `axonasp-http -c path.toml`. - **web.config is processed only if `enable_webconfig = true`, only from the web root, and only a subset of IIS** (`rewrite`, `httpRedirect`, `httpErrors`, and appSettings read by app code). Subdirectory web.config files are ignored. - Rewrite patterns use **Go RE2: no lookahead (`(?!...)`), no backreferences.** **[verified here]** a lookahead rule silently never matched. To exclude static files, use the `IsFile` / `IsDirectory` conditions instead. Supported condition inputs: `{REQUEST_FILENAME}`, `{URL}`, `{REQUEST_URI}`. Rewrites run before ASP execution. After a rewrite the server's `URL` is the rewritten target, so pass the original path in the query string (`__route`), as `public/web.config` does. - Application settings come from `GetAppSetting("Key")` (reads `web.config` appSettings). Keep secrets out of source control; prefer environment variables for credentials. - Locale is controlled by `Session.LCID` (default `global.default_mslcid`). Set it explicitly before `FormatDateTime`, `FormatNumber`, `FormatCurrency`. - AxonASP must not be exposed directly to the internet. Put IIS, Nginx or Caddy in front for TLS, and keep one AxonASP process per application (Application/Session state is in-process memory). --- ## 7. Migrations - Files live in `db/migrations/` and are named `YYYYMMDDHHMMSS_description.asp` (14-digit version). Each defines `Migration_Up(migration)` and `Migration_Down(migration)`. - Available helpers on `migration`: `ExecuteSQL`, `CreateTable`, `DropTable`, `AddColumn`, `DropColumn`, `CreateIndex`, `DropIndex`. - Every migration must be reversible and SQLite-compatible (section 5). Create a table before any migration that alters it; order is by version. - Run: `scripts\migrate.cmd status`, `up`, `down` (one step). The runner is `scripts/migrate.asp` using `Migrator_Class` in `core/lib.Migrations.asp`. - The migrator reports real errors and rolls back the transaction on failure. Do not reintroduce blanket `On Error Resume Next` there. - Never compare 14-digit versions with `CLng` (overflow); use `CDbl` or compare strings. --- ## 8. Gotchas found while porting (verified here) - **Stale code after edits.** AxonASP caches compiled scripts and includes (file watcher plus bytecode cache, `bytecode_caching_enabled` in `[global]`). During development, if an edit seems ignored or an error line number does not match the file, run `docker restart axonasp` (or set `GLOBAL_BYTECODE_CACHING_ENABLED=disabled`) before debugging further. - **Error line numbers can be wrong.** Errors inside included files or class members were reported against an unrelated file/line (often near the end of the last include). Bisect with small test pages and `Response.Write` markers rather than trusting the line. - **Do not call a parameterless Function as an object in statement form.** `MVC.DispatchRequest a, b` (where `MVC` is a Function returning an object) failed with "Object required". Use `MVC().DispatchRequest a, b`, or assign to a variable first: `Set m = MVC()`. The same applies to `router`, `Flash`, `Routes`, `DAL`, and any singleton accessor. Expression form (`x = MVC.Prop`, `TypeName(MVC)`) works. - **Reserved words as procedure names.** `put` is parsed as the file `Put #n` statement and breaks `put "text"`. Do not name Subs/Functions after VB statements (`Put`, `Get`, `Open`, `Close`, `Print`, `Input`, `Seek`, `Lock`, `Name`, `Kill`, ...). The framework's output helper is now `puts` / `puts_`. - **`ReDim` of a module-level array inside a Sub/Function does not reach the global.** The Sub got its own local array, and a later `UBound`/index on the global failed with "Subscript out of range" or "Stack underflow" (chunker, in this repo). Keep growable arrays as `Private` members of a Class (`Chunker_Class` in `core/lib.Search.asp`) and expose accessor functions. Also keep every `If ... Then <call>` multi-line. - **Class-level `Const` is Empty.** `Private Const X = 10` inside a `Class` evaluates to Empty in methods (no error, so e.g. `per_page` silently became 0 and paging broke). Declare `Const` at top level, outside the class, with a prefixed name. - **G3JSON.Parse and G3DB interfere under the HTTP server.** Verified: parsing a request body with `G3JSON.Parse` before the first database open in the process made the first INSERT silently do nothing (201 with `id` 0, no row), and only on the first POST after a restart; opening the database first made `Parse` return dictionaries whose `Exists`/`Item` returned stale values. Dictionaries built in a Function and returned also came back empty, and the first native call after another native call could return the previous value. For API controllers use `core/lib.JsonLite.asp` (pure VBScript: `JsonLite_Parse` -> object with `.Exists(k)`/`.Item(k)` (call `.Item`, there is no default member), `JsonLite_Quote`, `JsonLite_Num`) and compose output JSON as text. Plain VBScript classes are safe; native objects held across other native calls are not. - **`Request.BinaryRead(n)` returns one character per byte** (raw UTF-8 bytes), not decoded text. Decode UTF-8 yourself (`Utf8Decode` in the API controllers, which maps invalid bytes to U+FFFD); `ADODB.Stream` was unreliable too. `MSXML2.ServerXMLHTTP` works in the CLI for calling the local server, which is a handy way to write an HTTP smoke test (`axonasp-cli -r script.asp` inside the container, base URL `http://localhost:8801`). - **The dispatcher swallows action errors.** `Dispatch`/`ExecuteControllerAction` in `core/mvc.asp` run under `On Error Resume Next`, so an error inside an action aborts it and the response is an empty `200` (or a half page) with no message. For write paths wrap the DB call in a local `On Error Resume Next`, check `Err.Number` straight after it and answer with a real error (the API controllers send a JSON 500 via `DbFailed`). When something "does nothing", test the same code from a plain page or the CLI to see the real error. - **Always test cold.** After `docker restart axonasp`, send the write request (POST/PUT/DELETE) first, before any GET: some bugs only appear on the first request after a start. Debugging aid: `Response.Clear` wipes the body, but `Response.AddHeader "X-Dbg-1", "..."` survives, so trace with headers (`curl -i`). When patching with scripts, assert that each replacement matched (a silent no-op edit cost hours here). - **Operator precedence:** `"ok=" & Not (x Is Nothing)` raises Type mismatch. Put the `Not ...` in a variable first. - **Response after the layout header:** the layout header is already in the buffer when an action runs, so `Response.Clear` before `Response.Redirect`, and for non-HTML actions set `useLayout` to False (the API controllers do). - **Static files under `public/`** (for example `public/api/*.openapi.json`) are served directly; the rewrite rule skips existing files and directories. Only routes in `public/Default.asp` go through the MVC dispatcher; a route needs the controller in `autoload_controllers.asp` **and** in `ControllerRegistry` (the generators do both). - **Swagger UI:** the multi-spec dropdown (`urls: [...]`) only works with `presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset]` and `layout: "StandaloneLayout"`. Without them the page says "No API definition provided". - **Git Bash:** `curl` sends non-ASCII literals as cp1252, not UTF-8 (use `\u00fc` escapes or a file with `--data-binary @file`); read CSRF tokens from the form with a cookie jar (`-c/-b`); strip `\r` from values printed by Python on Windows before putting them in URLs. Python on Windows also reads piped stdin as cp1252: tests that compare non-ASCII text must call `sys.stdin.reconfigure(encoding='utf-8')` (`python -I` ignores `PYTHONIOENCODING`). - **405 and API 404s come from the router.** `Router_Class.Resolve` returns `ErrorController.MethodNotAllowed` (with an `Allow` header) when the path is routed for other methods; `ErrorController` answers `/api/...` requests with the JSON error format and no layout. Routing happens before authentication, so a wrong method is 405 even without a key. - **`Api_ToInt` clamps** to its range instead of rejecting, so use it for limits and paging only; validate values that must be rejected when out of range (for example `?revision=`) explicitly. - **SQLite NOT NULL columns and the 8-parameter limit.** Every NOT NULL column without a default must be in the INSERT; when the parameters run out, inline server-generated values that cannot contain user input (for example `Api_Now()` timestamps) rather than moving them to the follow-up UPDATE. - **Include order matters for class methods.** A class method cannot see a global Function/Class defined in a file included *after* the class's file (`GetRouter()`, `Flash()` failed with "Object required" / "doesn't support this property or method"). `core/autoload_core.asp` therefore includes `mvc.asp` last. - **Dynamic Eval/Execute in classes is unreliable.** `Eval`/`Execute` inside a Class method cannot see global functions; with a runtime-built string they re-emit a method's inline HTML twice (second copy after the footer); `CallByName` is a silent no-op. Do not dispatch with them. - **Call sites bind to the first class.** `CurrentController.Invoke ...` in one place was bound to the first controller's `Invoke` and reused for every later controller (the first dispatched action's body appeared on every route; title/layout were right). Each controller therefore exposes a global `<Name>Controller_Invoke(actionName, args)` and the dispatcher calls it through `GetRef` (`MVC_InvokeAction`). New controllers must define `Invoke` and `<Name>Controller_Invoke` (the generators emit both). - **Single-line `If x Then a = b Else a = c` swallowed the rest of a Sub** under `On Error Resume Next`. Always use multi-line `If`. - **Migrator: one migration per process.** `migrate.cmd up` with two or more pending migrations failed on the second one (`Runtime error: Migrator '800A0002'`; an AxonASP VM panic "assignment to entry in nil map" when reproduced in a plain script). Run `migrate.cmd up` once per pending migration. Even a successful apply/rollback currently ends with `Object required` from `core/helpers.asp` and exit code 1 (reproduced on the original unmodified framework, so not caused by local changes); check `migrate.cmd status` rather than the exit code. - **Close a result set before running another statement.** Running a query inside a loop over an open G3DB result set hung the request (script timeout), and a write executed while a result set was still open was silently lost (the `provision key` action created no key). Copy the values you need, `rs.Close`, then query/write. - **G3DB takes at most 8 parameters per statement** ("Too many parameters (12); the maximum is 8"). Split wide INSERTs into an INSERT plus an UPDATE inside one transaction (see `InsertRevision` in `ApiMemoriesController.asp`). - **Characters above U+FFFF (emoji) cannot be held** on the pinned build (CLI v2.3.42): `ChrW(128512)` raises "Invalid procedure call" (older builds returned one character), and `ChrW(55357) & ChrW(56832)` is written out as CESU-8 (`ED A0 BD ...`), which is invalid UTF-8. `Api_Utf8Decode` and JsonLite therefore flag such code points (raw 4-byte UTF-8 or escaped surrogate pairs) and `Api_ReadBody` answers 422 `unsupported_character`; the generator template does the same. Do not store them as U+FFFD silently. - **Calling HTTP services from a request works alongside G3DB** (verified with `MSXML2.ServerXMLHTTP` to Ollama and Qdrant, reads and writes before and after, cold first request). Set `SetTimeouts` so a dead service cannot hang the request, never let an HTTP failure fail a database write, and keep large JSON (vectors) as text: slice it with `InStr`/`Split` instead of parsing it with JsonLite. - **Embedding similarity thresholds are model-specific.** With `nomic-embed-text` (and its `search_query: `/`search_document: ` prefixes) relevant pairs scored 0.61-0.67 and unrelated ones up to 0.58, hence `EmbeddingMinScore` 0.6. Re-measure before changing the model, and remember the memory title is part of the embedded (and FTS-indexed) text. - **`AscW` is signed:** characters U+8000..U+FFFF give negative values, so `AscW(c) > 127` misses them (fixed in `Search_FtsQuery`). The same applies to `CLng("&H" & hex)` for 4-digit hex. - **`content_hash` is not a content hash.** `memory_revisions.content_hash` is SHA-256 of `namespace|type|title|content` (used for duplicate detection in one namespace). To dedupe the same text across namespaces compare the content itself (as `ApiContextController` does). - **Agent tooling can rewrite escape sequences.** In this repo's sessions, `\uXXXX` written in a tool command or file edit was sometimes decoded to the real character before bash/curl ran (curl then sent `??`), which looked like a server bug. Produce backslashes at run time in tests (`printf '%su00fc' '\'`, Python `chr(92)`), check test files for unintended non-ASCII bytes, and confirm what curl sends with `--trace-ascii -` before blaming the runtime. - **Run CLI tools as the server user.** The HTTP server runs as `axonasp`; a database file first created by a root `docker exec` was read-only to it ("attempt to write a readonly database"). `gen.cmd`, `migrate.cmd` and `provision.cmd` use `docker exec -u axonasp`. - **PowerShell splits `read,write` into two arguments.** Quote lists passed to `provision.cmd grant`: `'"read,write"'`. - **Class member vs local name clash.** Avoid a local `Dim controllerName` inside a class that also has a `ControllerName` property. - **`Empty Is Nothing` raises "Object required".** Test with `IsObject` / `IsEmpty` first, then `Is Nothing`. - **`Server.Execute(file)` runs the file as a separate page.** It does not define procedures in the caller's scope. To load a script's Subs, read the file and `ExecuteGlobal` the text (strip `<%`/`%>`), as the migrator does. - **CLI differences.** `axonasp-cli -r file.asp` runs ASP; `-m vbscript` runs pure `.vbs` (no `WScript`). The CLI's web root comes from config (`SERVER_WEB_ROOT`), `Server.MapPath` is relative to the script's folder, relative `..` is clamped to the web root, and `FileSystemObject` cannot leave the web root. Run CLI tools with `-e SERVER_WEB_ROOT=<framework folder>` and use `Server.MapPath("/...")`. - **Git Bash on Windows rewrites `/opt/...` arguments** passed to `docker exec`. Prefix with `MSYS_NO_PATHCONV=1`, or run from `cmd`/PowerShell. - **Containers run as root with bind mounts.** Files created by the server (for example `db/app.sqlite`) are owned by root inside the container; this is fine on Windows hosts. --- ## 9. Security checklist - Validate and whitelist every controller and action name before `Execute`/`Eval` dispatch (the registry in `core/lib.ControllerRegistry.asp` does this). Never build code or SQL from raw request input. - Parameterize SQL. Never accept table or column names from users. - `Server.HTMLEncode` all output derived from input, headers, DB data and errors. - Do not show `ASPError` details (file, line, source) to end users in production. Log them instead; custom pages go through `httpErrors` in `web.config`. - Keep `blocked_extensions` / `blocked_dirs` in the container's `axonasp.toml` intact. Do not place secrets, `.sqlite` files or migrations under the web root (`public/`). - Do not enable `allow_external_filesystem_access` unless a trusted need is documented. - Use `G3CRYPTO` for hashing and tokens. Do not roll your own. - The generated JSON APIs are **unauthenticated and have no CSRF protection** (stateless by design). Put authentication in front of them before exposing the app, and keep HTML form posts on the CSRF token (`HTMLSecurity()`). --- ## 10. Working rules for agents in this repo - **Use the provided scripts; do not hand-create what they generate.** New migration -> `scripts\gen.cmd migration`; model + repository -> `scripts\gen.cmd repo`; JSON API (controller, routes, whitelist, includes, OpenAPI spec, `.http` file) -> `scripts\gen.cmd api`; HTML controller stub with routes -> `scripts\gen.cmd controller`; schema changes -> `scripts\migrate.cmd up|down|status`. Edit generated files afterwards (migration bodies, business rules, views), but never write a controller, repository, POBO, route, whitelist entry or migration file from scratch when a generator exists, and never change the schema outside a migration. If a generator is missing a feature or produces something wrong, fix the generator/template in `scripts/` (and say so) instead of patching the output only. - **The scripts need Docker.** `gen.cmd` and `migrate.cmd` run `docker exec ... axonasp ./axonasp-cli`, so Docker must be running and the `axonasp` container up (`docker compose up -d` from the repo root) before using them. If it is not running, start it or tell the user; do not fall back to hand-writing the files. Run them from PowerShell or cmd, not Git Bash. Generators only write files: `docker restart axonasp` afterwards. - Make the smallest change that solves the problem. Match the style of the file you are editing. - After changing ASP code, restart the container, then verify in the running app (`curl localhost:8801/...`) before claiming success. Report real output and real errors. - Test every new endpoint through the whole range: happy path, validation (422), bad input (400), unknown id (404), wrong method (405), HTML-escaping, UTF-8 round trip, and a cold first request after a restart. JSON APIs: curl, the generated `api-tests/<table>.http` and the Swagger page `/api/docs`. - Clean up test data and throwaway tables/migrations/generated files you created while experimenting (roll back with `migrate.cmd down` first), and leave the database as you found it. - When a bug does not make sense, stop patching around it: reduce it to a small page, change one variable at a time, and write the finding into section 8. - Do not add `On Error Resume Next` to silence an error. Surface it. - Keep new code to the portable subset in section 2 unless the user asks for AxonASP extensions. - Do not modify anything under `/opt/axonasp` in the container except the mounted `site/` folder. - Ask before deleting migrations, the database file, or anything under `db/`.