{
  "$schema": "./schemas/semantics.schema.json",
  "name": "AIScript",
  "version": "1.0.0-draft.1",
  "codingContract": [
    "The grammar, types, semantics and declared interface contracts define AIScript. Use exact names, argument order, accepted types and return types.",
    "Do not infer methods from another language. Host-language imports, reflection and dynamic code evaluation are not available.",
    "The author owns business design. Combine supported capabilities freely. Identify a precise missing capability rather than invent an interface.",
    "Before delivery, correct known syntax, type and interface errors in the actual implementation. Explanations do not replace complete code."
  ],
  "rules": [
    {
      "name": "Process And Code",
      "rules": [
        "A System still has its manifest, Collections, Audiences, Services, Secrets, Events and Processes. Their resource specifications remain separate from the programming language.",
        "../../Process.md defines the Process contract. It owns Inputs, Outputs, Audience, invocation, authentication and App presentation. Code implements that contract. It contains no endpoint specification, access policy, listener installation or deployment configuration.",
        "AIScript code is a separate .ais resource, normally processes/<name>/code.ais. It contains one execute(input) function and any number of helpers. The resource path is relative to the System root, not to this documentation folder.",
        "execute receives the declared Inputs. Its returned value must match the declared Outputs. A helper returns a value to its caller, not to the external client. Helpers may appear before or after their callers. There are no executable statements or variables outside functions.",
        "No business domain, resource count, workflow shape or implementation strategy is prescribed by this language."
      ]
    },
    {
      "name": "Source And Blocks",
      "rules": [
        "Source is UTF-8. Names are case-sensitive.",
        "Function and variable names use letters, digits and underscores, beginning with a letter. Resource names are string values and follow the System resource naming rules.",
        "A function starts with its name and parameters and ends with end. There is no function, fn or to keyword.",
        "Statements end at a newline. Within parentheses, brackets or braces, a newline continues the expression. Indentation is for readability and has no execution meaning. Semicolons are not used.",
        "A block introduced by if, for each, while, switch, try, async or timer ends with end.",
        "Strings use double quotes and JSON escapes. Numeric literals are base ten; a decimal point or exponent makes a decimal literal. A leading minus is unary negation.",
        "Object keys can be unquoted names or quoted strings. Duplicate literal keys are an authoring error.",
        "Comments are // to the end of a line or /* ... */ across lines. Block comments do not nest. Comment markers inside strings are text.",
        "Definitions are recognized at file level. A similar name(arguments) form inside a function is a call. Function names, parameters, utility namespaces and execution-context names cannot be ambiguously reused in the same scope."
      ]
    },
    {
      "name": "Variables And Functions",
      "rules": [
        "name = value creates or updates a local variable. Parameters are local variables. No declaration keyword is needed. Assignment to an existing variable must preserve its compatible type; integer-to-decimal promotion is allowed. A nullable value may alternate between its value type and null.",
        "Variables belong to a function call, not to a shared Process object. An assignment in an ordinary conditional or loop updates that function's local variable. A variable must be assigned on every possible path before it is read. Loop item names exist only within their loop; they cannot hide an existing local name. Helpers do not capture their caller's variables: pass arguments explicitly.",
        "Primitive values are passed by value. Objects and arrays are shared by reference within one execution. Object.copy(value) creates an independent deep copy of data. Service and resource handles passed to helpers continue to refer to their original execution-owned resources. Async has a separate copy boundary described in this contract.",
        "Helpers have fixed positional parameters and no hidden optional parameters. A helper may return a value or return without a value, but not mix both styles. A no-value call is a statement and cannot be assigned or used in an expression. Falling through a no-value helper is equivalent to return. Every successful path through execute must return its result, including an explicitly empty result when its contract has no Outputs.",
        "Types come from Inputs, Outputs, Collection fields, method signatures and expressions. Runtime checks handle data whose shape is unknown until execution. Unknown data is not permission to invoke undocumented methods. Recursion is allowed; operational limits govern execution time, call depth and memory, not the number of business resources in a design."
      ]
    },
    {
      "name": "Values",
      "rules": [
        "Collection references and File values retain their resource-defined shapes. Resource type text maps to the string code type; resource type long maps to the checked integer code type. An identifier is a string or integer according to its Collection; it is not an additional primitive type. A File Input is metadata, not bytes and not a storage handle. There is no competing number code type.",
        "Services, records, cursors, protocol messages, mail, channels, files and streams are typed handles. Only their specified fields and methods are accessible. Reflection, prototypes, host-class construction/imports and dynamic code evaluation are not part of AIScript.",
        "A Service contract's lookupParameters defines the type and requiredness of the object after service \"name\" with. Its property names and values must match that definition; protocol names reference the configured Service's declarations.",
        "object.name and object[key] access one property. Missing object properties read as null. Object.has(object, key) distinguishes a missing property from an explicit null. Reading through null fails with InvalidInput; it does not create intermediate objects. Arrays use zero-based checked integer indices. An invalid index fails rather than producing an undefined value.",
        "Assignments to object properties and existing array positions update those values. array.add(value) adds one item at the end and has no result. It is a statement-only method call: do not assign, return or chain its result. The value must match the array's declared item type when one is specified. Explicit null properties must survive copies and permitted serialization."
      ]
    },
    {
      "name": "Expressions And Calculations",
      "rules": [
        "Operands and call arguments evaluate once, from left to right. and and or short-circuit. Precedence, from strongest to weakest, is:",
        "1. Member/index access and calls.\n2. Unary minus and not.\n3. *, /, %.\n4. +, -.\n5. ==, !=, <, <=, >, >=.\n6. and.\n7. or.",
        "Parentheses override precedence. Conditions must be boolean. Numeric comparison compares values, including integer/decimal promotion; strings compare Unicode code-point sequences. Dates and datetimes compare only with the same type. Null supports equality and inequality, not ordering. Structured equality is explicit through Object.equal, not handle identity or an inherited host-language rule.",
        "Integer addition, subtraction, multiplication, negation and remainder are exact within the signed 64-bit range. Overflow fails with InvalidInput. % accepts integers and has the dividend's sign. Decimal addition, subtraction and multiplication use exact decimal intermediates. Mixing integer and decimal promotes the integer. Division produces a decimal; zero divisors fail. / requires a terminating decimal result. For rounded division, use divide(value, divisor, places, rounding).",
        "The aggregation binds its item name explicitly. Its source is an array, it evaluates each projected numeric value once, and an empty source returns the zero of the inferred numeric type. A non-numeric item fails. It does not infer a query or fetch more records.",
        "round(value, places, rounding) and divide(value, divisor, places, rounding) return decimals. places is a non-negative integer. Rounding names are half-up, half-even, up, down, ceiling, floor and unnecessary. Up/down mean away from/toward zero; ceiling/floor mean toward positive/negative infinity. unnecessary fails if rounding would change the value. Precision is not silently selected from a currency or from the machine locale.",
        "+ also concatenates two strings. There is no implicit string/number conversion, loose equality, NaN or infinity.",
        "Integer and decimal literals retain their source digits. Calculations do not silently convert an exact integer or decimal into an approximate value.",
        "Numeric serialization preserves the value's digits. Non-finite values fail. A declared numeric Output is not silently converted to a string; use explicit conversion when the Output contract requires text."
      ]
    },
    {
      "name": "Control Flow",
      "rules": [
        "for each item in values visits an array in order or consumes a cursor in its documented forward order. while condition tests before each iteration. break exits the nearest loop; continue advances it. Changing an array's length while iterating that same array is an error; construct another array or iterate a copy.",
        "switch value contains case expression clauses and an optional else clause. Cases are evaluated in order; the first equal scalar value runs. There is no fall-through. One end closes the switch. No match without else does nothing.",
        "return value exits the current function. return without a value is allowed only in a no-value helper. execute must return the shape specified by its Process."
      ]
    },
    {
      "name": "Eight Failures",
      "rules": [
        "fail Name message evaluates the string message and raises that named failure. These are the only failure categories. An ordinary business outcome such as a declined application belongs in declared Outputs. Authentication and access management remain runtime responsibilities; listing failure names does not move those responsibilities into business code.",
        "Uncaught failures propagate automatically. Use catch only when handling a failure, not just to throw it again. The fail statement creates a named failure; throw failure propagates an existing caught failure when handling cannot resolve it. throw does not take a failure name and message. Cleanup belongs in finally; cleanup alone does not require a catch.",
        "try may have ordered catch Name clauses, a final catch failure for any remaining failure, and/or finally. A named clause handles exactly that category. A general catch binds an immutable object with name and a safe message; internal causes remain diagnostic information. throw failure preserves the caught failure. No explicit return, fail, throw or control-flow escape is permitted in finally. If cleanup itself fails while another failure is propagating, preserve the original failure and attach the cleanup failure to internal diagnostics. A cleanup failure without a prior failure propagates normally.",
        "Unsupported arguments and failed conversions map to InvalidInput. A unique-constraint or state conflict maps to Conflict. Explicit permission denials map to Forbidden. Network timeouts and temporary provider failures map to Unavailable. Unexpected execution failures map to InternalError. An HTTP response with an unsuccessful status is still a response; the author interprets its business meaning. Failure categories do not depend on matching human-readable messages.",
        "Catching a failure does not undo side effects. A database failure that leaves its transaction unusable makes that execution scope rollback-only. Catching it cannot turn the scope into a successful commit. There is no automatic retry, rollback compensation or remote failover."
      ]
    },
    {
      "name": "Execution Context And Results",
      "rules": [
        "property(path, fallback = null) reads local System properties. There are no mandatory business property names. Secret locations and key identifiers always use the security.secrets prefix.",
        "call \"ProcessName\" with inputs invokes a declared same-System Process and returns its typed Outputs. Its name is a resource reference, not a URL or generated ID. It must be callable on the internal channel. Publication resolves routing; code does not assemble paths. Cross-System communication uses a declared Service. Direct child calls and ordinary helpers do not independently commit shared database work.",
        "Ordinary results use return object. Additional forms are return text string, return bytes bytesValue, return file storageFile and return redirect url. A File metadata Output uses ordinary structured return, not return file. A redirect is restricted to HTTP(S), does not imply authentication and does not itself complete a later callback.",
        "Each return can have with metadata, an object with optional status, contentType, filename and headers. Status is one of ok/created/accepted/noContent/seeOther/temporaryRedirect or an explicit valid HTTP status for a documented integration requirement. These are response metadata, not extra failure names or endpoint specifications. JSON/text/bytes/file default to status ok; redirect defaults to seeOther. JSON defaults to application/json and text to text/plain with UTF-8. Bytes require contentType, and file uses explicit metadata or its declared content type. noContent requires null as the returned body. filename is a suggested download name, not a filesystem path. Headers cannot override hop-by-hop headers or contradict the selected body encoding. Filename/header values containing CR, LF or NUL fail; download names cannot contain path separators. Typed result validation still applies to the Process's selected transport response contract.",
        "Body access must retain original bytes for verification. A typed internal invocation may have structured Inputs without an original byte sequence; bytes() then returns null. Callback/body/parameter mapping is explicit in the Process integration contract; accessors do not invent it. There is no identity administration or request-principal binding logic in this language contract."
      ]
    },
    {
      "name": "Transactions, Async And Timers",
      "rules": [
        "The runtime owns the request database transaction. Reusing the same database Service in that context, including through direct child calls, shares its transaction. Saving a record does not commit. Success commits and error completion rolls back, subject to rollback-only state. Separate database Services are not an automatic distributed transaction. HTTP, mail, cache, storage and messaging effects do not roll back with it.",
        "Async copies the captured data values at submission, returns immediately and never retains the caller's request, response, transaction or Service instances. Captured dates, integers and decimals preserve their types and precision. A handle cannot cross this boundary, including through a helper or nested object. The async block can modify its own copied values but cannot mutate the parent's variables.",
        "Each async block has an independently owned execution scope. A Service is obtained by the same service \"name\" syntax inside that scope, including within a helper. Its database transaction is separate from the caller's. The same runtime access rules apply; async does not grant new permissions. No handle crosses scopes.",
        "Services acquired inside async belong to that async execution and are released when it ends. They are never borrowed from the caller.",
        "Work may start before the parent commits. Async is not after-commit, durable, exactly-once or automatically retried. Its failure is collected under the originating activity correlation, but cannot change a response already sent. Shutdown stops accepting new work and requests cooperative cancellation of running work; it does not promise to finish or replay it. Durable business stages require stored work and separately invoked Processes.",
        "timer interval unit timeout amount unit repeat count is valid only within async. Timeout and repeat are independently optional, but at least one is required. Units are milliseconds/seconds/minutes/hours; amounts and repeat are positive integers. It waits before the first iteration, runs sequentially and starts no iteration after its timeout or repeat budget is exhausted. The bounds do not preempt an in-progress blocking call; that call needs its Service timeout.",
        "stop exits the nearest Timer successfully. Exhaustion without stop raises Unavailable in the async scope. The Timer preserves its own plain-data state between iterations. Each iteration owns a fresh Service/transaction scope and releases it before waiting again; handles cannot enter from outside an iteration or survive into another. Data assignments may persist; handles may not. This avoids holding a database transaction open while waiting. A Timer is still in-memory and not a replacement for scheduled Process invocation."
      ]
    },
    {
      "name": "Comments And Descriptive Annotations",
      "rules": [
        "Comments explain business decisions and meaningful operations, not every punctuation mark. Keep them beside the operations they describe.",
        "@Standard and @Conformance describe business/protocol standards and implemented behavior. These lines remain comments, not endpoint specifications, permissions, security configuration or proof of certification. Do not add irrelevant annotations or invented requirement numbers."
      ]
    },
    {
      "name": "Consistency",
      "rules": [
        "The code must agree with its Process Inputs, Outputs, dependencies and documented behavior. References use exact resource names. Every field, method, Event payload and Process call must match its declared interface. Do not replace an intended integration with fictional results.",
        "The author owns business completeness and consistency across resources. The specifications do not prescribe a business scope, a resource count or a payment-specific design."
      ]
    },
    {
      "name": "Grammar",
      "rules": [
        "This grammar defines source structure. Semantic rules in this contract constrain otherwise valid syntax. NEWLINE means a logical newline outside strings and bracketed expressions. Blank lines and comments are ignored. A statement before end/else/case/catch/finally still ends with a logical newline. Source indentation does not create a block. Trailing commas in source argument, array and object lists are accepted; JSON text parsed by Object.parse remains strict JSON.",
        "An expression statement must be a call with effects; an unused literal is an error. A switch requires at least one case. A try requires a catch or finally. Finally, fail/throw, mutation and resource operations have the scope/type restrictions defined in this contract. Names matching control-flow keywords, failure names, builtin functions or utility namespaces cannot be redeclared. The return-format words text/bytes/file/redirect are contextual keywords only immediately after return. Keywords may appear as unquoted object keys because that position is unambiguous.",
        "Function names and bare helper references resolve before execution. There is no function overloading by arity, implicit recursion capture or dynamic code generation. A malformed program is rejected rather than executed as another language."
      ]
    }
  ],
  "failures": [
    "InvalidInput",
    "Unauthenticated",
    "Forbidden",
    "NotFound",
    "Conflict",
    "LimitExceeded",
    "Unavailable",
    "InternalError"
  ],
  "hostBoundary": "Only declared AIScript functions, core operations, Utilities and acquired Services are callable. Strings and comments are data, never executable source.",
  "failureBehavior": {
    "InvalidInput": {
      "purpose": "Supplied data is invalid.",
      "httpStatus": 400
    },
    "Unauthenticated": {
      "purpose": "Authentication is missing or invalid.",
      "httpStatus": 401
    },
    "Forbidden": {
      "purpose": "The operation is not permitted.",
      "httpStatus": 403
    },
    "NotFound": {
      "purpose": "The requested resource does not exist.",
      "httpStatus": 404
    },
    "Conflict": {
      "purpose": "The current state prevents the operation.",
      "httpStatus": 409
    },
    "LimitExceeded": {
      "purpose": "An applicable limit has been reached.",
      "httpStatus": 429
    },
    "Unavailable": {
      "purpose": "A required capability is temporarily unavailable.",
      "httpStatus": 503
    },
    "InternalError": {
      "purpose": "An unexpected execution failure occurred.",
      "httpStatus": 500
    }
  },
  "annotations": {
    "Security": "Applicable security standard.",
    "Requirement": "Verified requirement identifier when known.",
    "Control": "Protection actually implemented.",
    "Evidence": "Operation providing evidence.",
    "Standard": "Business or protocol standard.",
    "Conformance": "Implemented behavior; not independent certification."
  },
  "typeExpressions": {
    "reference": "A namespace-qualified type name resolves to exactly one declared type.",
    "arrayOf": "An ordered array whose every item satisfies the referenced type.",
    "nullable": "The referenced type or null. Optional argument presence is separate from nullability.",
    "oneOf": "A union of the listed disjoint value kinds. It does not introduce another primitive type.",
    "objectSchema": "Every object type has a JSON Schema describing its data structure. Open properties are allowed only as declared by that schema.",
    "inference": "Local expression types come from Process contracts, literals, operations and interface results. Record fields specialize from their declared Collection and loaded projection.",
    "handles": "Handles are not data objects, cannot be forged from serialized fields and expose no implicit host methods.",
    "arguments": "Arguments are positional and evaluate once from left to right. Required parameters cannot follow optional parameters. Variadic parameters appear only last. A missing argument uses its declared default or explicit profile behavior; omission is not automatically null.",
    "versions": "A System records the exact language and Service/Utility contracts it uses. A Runtime must support those versions before activation."
  }
}
