@mytechtoday/augment-extensions 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/AGENTS.md +4 -0
  2. package/README.md +86 -17
  3. package/augment-extensions/coding-standards/java/CHANGELOG.md +12 -0
  4. package/augment-extensions/coding-standards/java/README.md +54 -0
  5. package/augment-extensions/coding-standards/java/examples/SearchRequest.java +13 -0
  6. package/augment-extensions/coding-standards/java/metadata.json +36 -0
  7. package/augment-extensions/coding-standards/java/module.json +35 -0
  8. package/augment-extensions/coding-standards/java/rules/language-and-api-design.md +45 -0
  9. package/augment-extensions/coding-standards/java/rules/reliability-and-concurrency.md +43 -0
  10. package/augment-extensions/coding-standards/java/rules/testing-tooling-and-security.md +39 -0
  11. package/augment-extensions/coding-standards/spring/CHANGELOG.md +12 -0
  12. package/augment-extensions/coding-standards/spring/README.md +61 -0
  13. package/augment-extensions/coding-standards/spring/examples/OrderController.java +40 -0
  14. package/augment-extensions/coding-standards/spring/metadata.json +39 -0
  15. package/augment-extensions/coding-standards/spring/module.json +38 -0
  16. package/augment-extensions/coding-standards/spring/rules/beans-configuration-and-boot.md +39 -0
  17. package/augment-extensions/coding-standards/spring/rules/data-testing-and-transactions.md +36 -0
  18. package/augment-extensions/coding-standards/spring/rules/production-operations.md +40 -0
  19. package/augment-extensions/coding-standards/spring/rules/web-apis-and-security.md +43 -0
  20. package/augment-extensions/visual-design/metadata.json +1 -1
  21. package/augment-extensions/visual-design/module.json +2 -2
  22. package/augment-extensions/workflows/agent-engineering/README.md +67 -0
  23. package/augment-extensions/workflows/agent-engineering/examples/contracts.cjs +89 -0
  24. package/augment-extensions/workflows/agent-engineering/examples/demo.cjs +17 -0
  25. package/augment-extensions/workflows/agent-engineering/examples/evaluation-cases.json +7 -0
  26. package/augment-extensions/workflows/agent-engineering/examples/graphs.cjs +149 -0
  27. package/augment-extensions/workflows/agent-engineering/examples/loop.cjs +125 -0
  28. package/augment-extensions/workflows/agent-engineering/examples/recovery.cjs +51 -0
  29. package/augment-extensions/workflows/agent-engineering/examples/stub.cjs +11 -0
  30. package/augment-extensions/workflows/agent-engineering/examples/verify.cjs +21 -0
  31. package/augment-extensions/workflows/agent-engineering/module.json +24 -0
  32. package/augment-extensions/workflows/agent-engineering/rules/01-adoption.md +30 -0
  33. package/augment-extensions/workflows/agent-engineering/rules/02-agents.md +34 -0
  34. package/augment-extensions/workflows/agent-engineering/rules/03-contracts.md +34 -0
  35. package/augment-extensions/workflows/agent-engineering/rules/04-loops.md +39 -0
  36. package/augment-extensions/workflows/agent-engineering/rules/05-graphs.md +39 -0
  37. package/augment-extensions/workflows/agent-engineering/rules/06-improvement.md +38 -0
  38. package/augment-extensions/workflows/agent-engineering/schemas/contracts.schema.json +1 -0
  39. package/augment-extensions/workflows/agent-engineering/scripts/validate.cjs +32 -0
  40. package/augment-extensions/workflows/agent-engineering/sources.md +12 -0
  41. package/augment-extensions/workflows/agent-engineering/templates/agent.json +40 -0
  42. package/augment-extensions/workflows/agent-engineering/templates/check-tool.json +94 -0
  43. package/augment-extensions/workflows/agent-engineering/templates/evidence.json +29 -0
  44. package/augment-extensions/workflows/agent-engineering/templates/invocation.json +40 -0
  45. package/augment-extensions/workflows/agent-engineering/templates/node.json +27 -0
  46. package/augment-extensions/workflows/agent-engineering/templates/state.json +27 -0
  47. package/augment-extensions/workflows/agent-engineering/templates/task.json +40 -0
  48. package/augment-extensions/workflows/agent-engineering/templates/tool.json +52 -0
  49. package/augment-extensions/workflows/decision-layer/README.md +136 -0
  50. package/augment-extensions/workflows/decision-layer/examples/call-inventory.json +6 -0
  51. package/augment-extensions/workflows/decision-layer/examples/config.json +9 -0
  52. package/augment-extensions/workflows/decision-layer/examples/decision.json +13 -0
  53. package/augment-extensions/workflows/decision-layer/examples/labeled-cases.json +410 -0
  54. package/augment-extensions/workflows/decision-layer/examples/source.txt +3 -0
  55. package/augment-extensions/workflows/decision-layer/examples/task.json +8 -0
  56. package/augment-extensions/workflows/decision-layer/installation/package-lock.json +27 -0
  57. package/augment-extensions/workflows/decision-layer/installation/package.json +7 -0
  58. package/augment-extensions/workflows/decision-layer/installation/sources.json +18 -0
  59. package/augment-extensions/workflows/decision-layer/module.json +24 -0
  60. package/augment-extensions/workflows/decision-layer/rules/00-index.md +5 -0
  61. package/augment-extensions/workflows/decision-layer/rules/01-responsibilities.md +15 -0
  62. package/augment-extensions/workflows/decision-layer/rules/02-operation.md +13 -0
  63. package/augment-extensions/workflows/decision-layer/runtime/cli.cjs +70 -0
  64. package/augment-extensions/workflows/decision-layer/runtime/common.cjs +85 -0
  65. package/augment-extensions/workflows/decision-layer/runtime/contracts.d.ts +8 -0
  66. package/augment-extensions/workflows/decision-layer/runtime/decisions.cjs +198 -0
  67. package/augment-extensions/workflows/decision-layer/runtime/evaluate.cjs +61 -0
  68. package/augment-extensions/workflows/decision-layer/runtime/install.cjs +186 -0
  69. package/augment-extensions/workflows/decision-layer/runtime/integrations.cjs +64 -0
  70. package/augment-extensions/workflows/decision-layer/runtime/runner.cjs +201 -0
  71. package/augment-extensions/workflows/decision-layer/runtime/worker-child.cjs +15 -0
  72. package/augment-extensions/workflows/decision-layer/runtime/workers.cjs +15 -0
  73. package/augment-extensions/workflows/decision-layer/schemas/config.schema.json +27 -0
  74. package/augment-extensions/workflows/decision-layer/scripts/validate.cjs +16 -0
  75. package/augment-extensions/workflows/decision-layer/sources.md +25 -0
  76. package/cli/MODULES.md +804 -302
  77. package/cli/dist/__test_file-tracking.d.ts +2 -0
  78. package/cli/dist/__test_file-tracking.d.ts.map +1 -0
  79. package/cli/dist/__test_file-tracking.js +4 -0
  80. package/cli/dist/__test_file-tracking.js.map +1 -0
  81. package/cli/dist/analysis/ast-parser.d.ts.map +1 -1
  82. package/cli/dist/analysis/ast-parser.js +25 -9
  83. package/cli/dist/analysis/ast-parser.js.map +1 -1
  84. package/cli/dist/cli.js +5 -2
  85. package/cli/dist/cli.js.map +1 -1
  86. package/cli/dist/commands/decision.d.ts +4 -0
  87. package/cli/dist/commands/decision.d.ts.map +1 -0
  88. package/cli/dist/commands/decision.js +32 -0
  89. package/cli/dist/commands/decision.js.map +1 -0
  90. package/cli/dist/commands/gui-decision.d.ts +6 -0
  91. package/cli/dist/commands/gui-decision.d.ts.map +1 -0
  92. package/cli/dist/commands/gui-decision.js +189 -0
  93. package/cli/dist/commands/gui-decision.js.map +1 -0
  94. package/cli/dist/commands/gui-module-manager.d.ts +14 -0
  95. package/cli/dist/commands/gui-module-manager.d.ts.map +1 -0
  96. package/cli/dist/commands/gui-module-manager.js +326 -0
  97. package/cli/dist/commands/gui-module-manager.js.map +1 -0
  98. package/cli/dist/commands/gui.d.ts +3 -9
  99. package/cli/dist/commands/gui.d.ts.map +1 -1
  100. package/cli/dist/commands/gui.js +7 -293
  101. package/cli/dist/commands/gui.js.map +1 -1
  102. package/cli/dist/commands/link.d.ts +2 -0
  103. package/cli/dist/commands/link.d.ts.map +1 -1
  104. package/cli/dist/commands/link.js +82 -84
  105. package/cli/dist/commands/link.js.map +1 -1
  106. package/cli/dist/commands/search.js +1 -11
  107. package/cli/dist/commands/search.js.map +1 -1
  108. package/cli/dist/commands/unlink.d.ts +2 -0
  109. package/cli/dist/commands/unlink.d.ts.map +1 -1
  110. package/cli/dist/commands/unlink.js +51 -45
  111. package/cli/dist/commands/unlink.js.map +1 -1
  112. package/cli/dist/lib/module-resolver.d.ts.map +1 -1
  113. package/cli/dist/lib/module-resolver.js +2 -2
  114. package/cli/dist/lib/module-resolver.js.map +1 -1
  115. package/cli/dist/types/gui.d.ts +4 -0
  116. package/cli/dist/types/gui.d.ts.map +1 -1
  117. package/cli/dist/utils/coordination-queries.js +2 -2
  118. package/cli/dist/utils/coordination-queries.js.map +1 -1
  119. package/cli/dist/utils/decision-runner.d.ts +18 -0
  120. package/cli/dist/utils/decision-runner.d.ts.map +1 -0
  121. package/cli/dist/utils/decision-runner.js +114 -0
  122. package/cli/dist/utils/decision-runner.js.map +1 -0
  123. package/cli/dist/utils/extractCommandHelp.d.ts +2 -2
  124. package/cli/dist/utils/extractCommandHelp.d.ts.map +1 -1
  125. package/cli/dist/utils/extractCommandHelp.js +4 -4
  126. package/cli/dist/utils/extractCommandHelp.js.map +1 -1
  127. package/cli/dist/utils/file-tracking.js +5 -5
  128. package/cli/dist/utils/file-tracking.js.map +1 -1
  129. package/cli/dist/utils/glob-match.d.ts +6 -0
  130. package/cli/dist/utils/glob-match.d.ts.map +1 -0
  131. package/cli/dist/utils/glob-match.js +8 -0
  132. package/cli/dist/utils/glob-match.js.map +1 -0
  133. package/cli/dist/utils/gui-helpers.d.ts.map +1 -1
  134. package/cli/dist/utils/gui-helpers.js +7 -3
  135. package/cli/dist/utils/gui-helpers.js.map +1 -1
  136. package/cli/dist/utils/module-system.d.ts +2 -0
  137. package/cli/dist/utils/module-system.d.ts.map +1 -1
  138. package/cli/dist/utils/module-system.js +24 -13
  139. package/cli/dist/utils/module-system.js.map +1 -1
  140. package/cli/dist/utils/modules-catalog.d.ts.map +1 -1
  141. package/cli/dist/utils/modules-catalog.js +5 -0
  142. package/cli/dist/utils/modules-catalog.js.map +1 -1
  143. package/modules.md +72 -6
  144. package/package.json +30 -16
@@ -0,0 +1,39 @@
1
+ {
2
+ "version": "1.0.0",
3
+ "name": "spring-standards",
4
+ "displayName": "Spring Framework and Spring Boot Standards",
5
+ "description": "Practical Spring Framework and Spring Boot guidance for dependency injection, configuration, web APIs, transactions, testing, security, and operations.",
6
+ "type": "coding-standards",
7
+ "language": "java",
8
+ "tags": [
9
+ "spring",
10
+ "spring-framework",
11
+ "spring-boot",
12
+ "java",
13
+ "dependency-injection",
14
+ "configuration",
15
+ "spring-mvc",
16
+ "webflux",
17
+ "validation",
18
+ "transactions",
19
+ "spring-security",
20
+ "actuator",
21
+ "testing"
22
+ ],
23
+ "compatibility": {
24
+ "augmentMinVersion": "1.0.0"
25
+ },
26
+ "characterCount": 24030,
27
+ "lastUpdated": "2026-11-26",
28
+ "files": {
29
+ "rules": [
30
+ "beans-configuration-and-boot.md",
31
+ "web-apis-and-security.md",
32
+ "data-testing-and-transactions.md",
33
+ "production-operations.md"
34
+ ],
35
+ "examples": [
36
+ "OrderController.java"
37
+ ]
38
+ }
39
+ }
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "spring-standards",
3
+ "version": "1.0.0",
4
+ "displayName": "Spring Framework and Spring Boot Standards",
5
+ "description": "Practical Spring Framework and Spring Boot guidance for dependency injection, configuration, web APIs, transactions, testing, security, and operations.",
6
+ "type": "coding-standards",
7
+ "author": "Augment Extensions",
8
+ "license": "MIT",
9
+ "tags": [
10
+ "spring",
11
+ "spring-framework",
12
+ "spring-boot",
13
+ "java",
14
+ "dependency-injection",
15
+ "configuration",
16
+ "spring-mvc",
17
+ "webflux",
18
+ "validation",
19
+ "transactions",
20
+ "spring-security",
21
+ "actuator",
22
+ "testing"
23
+ ],
24
+ "files": [
25
+ "rules/beans-configuration-and-boot.md",
26
+ "rules/web-apis-and-security.md",
27
+ "rules/data-testing-and-transactions.md",
28
+ "rules/production-operations.md",
29
+ "examples/OrderController.java"
30
+ ],
31
+ "dependencies": [],
32
+ "augment": {
33
+ "characterCount": 24030,
34
+ "priority": "high",
35
+ "category": "coding-standards",
36
+ "language": "java"
37
+ }
38
+ }
@@ -0,0 +1,39 @@
1
+ # Spring Beans, Configuration, and Boot
2
+
3
+ Use the Spring container deliberately. Keep application behavior explicit and configuration external to compiled code.
4
+
5
+ ## Inject dependencies and manage beans
6
+
7
+ - Prefer constructor injection for required collaborators. It makes dependencies visible, supports immutable fields, and lets a plain unit test construct the class without starting a container.
8
+ - Use Spring-managed beans for application services and infrastructure that need container lifecycle, configuration, or framework integration. Do not retrieve dependencies from the application context inside business code.
9
+ - Define a bean with `@Bean` when configuring a third-party type or when explicit factory logic is clearer than component scanning. Keep configuration focused and deterministic.
10
+ - Choose singleton scope unless per-request or per-operation state requires another scope. A singleton service should not keep mutable request state in fields.
11
+ - Keep constructors and bean initialization fast and side-effect light. Perform network calls or other fallible startup work only through an explicit lifecycle design with defined failure and shutdown behavior.
12
+ - Avoid circular dependencies. Extract a shared responsibility or change the direction of the dependency rather than hiding the cycle with setter injection or lazy lookups.
13
+ - Use lifecycle callbacks only for lifecycle work. Ensure external resources created by a bean have a corresponding managed close or destroy path.
14
+
15
+ ## Structure Spring Boot applications clearly
16
+
17
+ - Use one primary `@SpringBootApplication` entry point and place it above the application packages it should discover. Add component scanning or auto-configuration exclusions only for a documented reason.
18
+ - Organize code around the application's domain or features when that makes ownership and changes easier to follow. Keep HTTP controllers thin and delegate use cases to application services.
19
+ - Let auto-configuration provide conventional infrastructure when it matches the application. Add explicit beans to replace behavior intentionally, not preemptively.
20
+ - When configuration is surprising, inspect the condition report with the supported Boot diagnostic options before excluding classes or copying internal auto-configuration details.
21
+ - Keep framework annotations at the integration boundary where possible. Avoid spreading container lookups and framework-specific types through domain logic without a need.
22
+ - Do not mix APIs or configuration conventions from different Spring Boot generations without checking migration notes, dependency management, and supported Java versions.
23
+
24
+ ## Externalize and validate settings
25
+
26
+ - Put environment-specific settings in supported external configuration sources. Do not compile hostnames, credentials, tokens, or environment-specific paths into application code.
27
+ - Bind related settings to a typed configuration object when that improves validation and discoverability. Use direct property injection for a small isolated value when it is consistent with the codebase.
28
+ - Validate required configuration at startup and fail with a clear, non-secret diagnostic. Define safe defaults only for values that are genuinely optional.
29
+ - Use profiles for intentional environment-specific configuration, not as a replacement for a clear configuration model. Understand property-source precedence before relying on overrides.
30
+ - Keep secrets in the deployment's approved secret mechanism. Avoid committing secret values in properties, YAML, test fixtures, or build files. Redact them in logs and diagnostic endpoints.
31
+ - Add a new configuration source or secret manager only when the deployment actually requires it.
32
+
33
+ ## Official references
34
+
35
+ - [Spring Framework dependency injection](https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html)
36
+ - [Spring bean lifecycle](https://docs.spring.io/spring-framework/reference/core/beans/factory-nature.html)
37
+ - [Spring Boot auto-configuration](https://docs.spring.io/spring-boot/reference/using/auto-configuration.html)
38
+ - [Spring Boot externalized configuration](https://docs.spring.io/spring-boot/reference/features/external-config.html)
39
+ - [Spring Boot system requirements](https://docs.spring.io/spring-boot/system-requirements.html)
@@ -0,0 +1,36 @@
1
+ # Spring Persistence, Testing, and Transactions
2
+
3
+ Put transaction and framework behavior at deliberate application boundaries, and test only the integration level each behavior needs.
4
+
5
+ ## Define transaction boundaries around use cases
6
+
7
+ - Place a transaction around an application operation that must commit or roll back as one unit. Keep the boundary on a Spring-managed service or application component rather than scattering it across controller methods.
8
+ - Review what the configured transaction manager controls. A database transaction does not automatically make HTTP calls, messages, files, or multiple independent stores atomic.
9
+ - Keep slow network calls and user interaction outside database transactions where possible. Holding a transaction open can retain locks and connections longer than necessary.
10
+ - Check the project's configured propagation, isolation, timeout, read-only, and rollback behavior. Do not assume that a method annotation alone gives the intended semantics for every exception or transaction manager.
11
+ - Understand proxy-based interception: calls made within the same object may not pass through the proxy. Avoid relying on an annotation for self-invocation; extract the transactional operation or use the documented programmatic approach when needed.
12
+ - Do not catch and suppress a failure inside a transaction if the caller expects rollback. Make rollback and retry policy explicit and safe for repeated execution.
13
+ - Keep persistence technology and repository APIs behind an application boundary where practical. Add Spring Data or another persistence project only when the application chooses it; it is outside this module's core scope.
14
+
15
+ ## Use the smallest Spring test context that proves the behavior
16
+
17
+ - Unit test domain and application logic without a Spring context when dependency wiring is not under test.
18
+ - Use a focused test slice for a web, persistence, or serialization boundary where the selected Spring version provides one. Keep the slice narrow and replace only external collaborators needed for isolation.
19
+ - Use `@SpringBootTest` when behavior depends on application configuration, auto-configuration, or interactions across several layers. Avoid loading the full context for every test.
20
+ - For web behavior, assert externally visible status, headers, and payload. For persistence, use isolated test data and verify constraints and transaction outcomes against the project's supported database setup.
21
+ - Test both success and failure paths, including validation, authorization, rollback, and startup configuration failures where those outcomes are contractual.
22
+ - Keep test properties deterministic and credentials fake. Do not weaken production security or transactions just to simplify a test.
23
+ - Verify test annotations and context setup against the exact Boot, Framework, JUnit, and test-library versions declared by the application.
24
+
25
+ ## Keep dependency management consistent
26
+
27
+ - Use the Spring Boot dependency management already selected by the project when available. Avoid pinning a Spring Framework or Spring test artifact independently without checking the supported dependency set.
28
+ - Add only the starter or testing support that is needed. Check whether the project already includes an equivalent dependency before suggesting another one.
29
+ - For a non-Boot Spring application, follow its existing dependency alignment and refer to the matching Framework documentation instead of assuming Boot's dependency management.
30
+
31
+ ## Official references
32
+
33
+ - [Spring declarative transaction management](https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative.html)
34
+ - [Using `@Transactional`](https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative/annotations.html)
35
+ - [Spring Boot testing](https://docs.spring.io/spring-boot/reference/testing/index.html)
36
+ - [Testing Spring Boot applications](https://docs.spring.io/spring-boot/reference/testing/spring-boot-applications.html)
@@ -0,0 +1,40 @@
1
+ # Spring Production Operations
2
+
3
+ Make runtime behavior diagnosable while keeping operational data and control endpoints protected.
4
+
5
+ ## Configure for each environment safely
6
+
7
+ - Keep operational settings outside the artifact and document required values, defaults, and validation. Fail startup when a required safety-critical value is missing or invalid.
8
+ - Use profiles and property sources intentionally. Verify precedence and active profiles in the exact Boot version rather than assuming a local configuration file wins.
9
+ - Set explicit connection, request, and shutdown timeouts for external resources using the settings supported by the chosen libraries. Bound queues and concurrency according to available capacity.
10
+ - Do not log secrets, full authorization headers, or sensitive request data. Use structured, consistently named fields and an appropriate request or trace identifier.
11
+
12
+ ## Add observability that answers operational questions
13
+
14
+ - Use the project's supported logging and observability integrations. Record failures with useful context and avoid logging the same exception at every layer.
15
+ - Expose health and metrics only to the monitoring system that needs them. Review endpoint access, exposure, sanitization, network binding, and authentication together.
16
+ - A health response should communicate actionable health without revealing environment values, credentials, or internal topology.
17
+ - Separate liveness from readiness. Liveness should reflect whether the process can continue; do not make it fail solely because a downstream service is temporarily unavailable. Readiness may reflect whether the application can safely receive traffic, according to its deployment contract.
18
+ - Do not add an observability backend or deployment platform as a prerequisite when the project has not selected one.
19
+
20
+ ## Expose Actuator deliberately
21
+
22
+ - Treat Actuator endpoints as operational interfaces. Expose only the endpoints the deployment requires, and control access using the supported security configuration.
23
+ - Review the data returned by environment, configuration, mappings, beans, loggers, and similar diagnostic endpoints before exposing them beyond a trusted boundary.
24
+ - Keep health detail and component indicators at the minimum level appropriate for the intended audience.
25
+ - Do not assume an endpoint is unavailable simply because it is not exposed over HTTP; review every configured management transport and port.
26
+ - Test access control and the public health contract in the production configuration profile, not only in a development profile.
27
+
28
+ ## Manage lifecycle and failure recovery
29
+
30
+ - Use framework lifecycle and graceful shutdown support so in-flight work can complete within the deployment's termination window.
31
+ - Make background work cancellable and bounded. Ensure executors and clients are closed when their owning context ends.
32
+ - Make retries explicit, bounded, and safe for duplicate execution. Avoid retrying non-idempotent operations without an idempotency design.
33
+ - Record startup and shutdown failures clearly while withholding secret configuration values.
34
+ - Check the current Spring Boot operations and Actuator documentation for settings supported by the application's exact release.
35
+
36
+ ## Official references
37
+
38
+ - [Spring Boot Actuator endpoints](https://docs.spring.io/spring-boot/reference/actuator/endpoints.html)
39
+ - [Spring Boot externalized configuration](https://docs.spring.io/spring-boot/reference/features/external-config.html)
40
+ - [Spring Boot system requirements](https://docs.spring.io/spring-boot/system-requirements.html)
@@ -0,0 +1,43 @@
1
+ # Spring Web APIs and Security
2
+
3
+ Keep transport concerns at the web boundary. Choose the web stack to match the application's I/O model and security requirements.
4
+
5
+ ## Choose MVC or WebFlux intentionally
6
+
7
+ - Prefer Spring MVC for conventional servlet applications, especially when the application and its dependencies use blocking I/O.
8
+ - Choose WebFlux when non-blocking request handling and reactive composition are requirements across the relevant call path. Evaluate client libraries, persistence access, streaming needs, operational skills, and measured workload before choosing it.
9
+ - Do not call blocking database, file, or network APIs on a reactive event loop. If a blocking boundary is unavoidable, isolate it using the supported scheduler and capacity controls for the project's Reactor and Spring versions.
10
+ - Avoid converting between imperative and reactive types repeatedly. A reactive controller does not make blocking dependencies non-blocking.
11
+ - Use the testing and client tools appropriate to the chosen stack. Check the current reference for supported test clients and server setup.
12
+
13
+ ## Design endpoints around validated contracts
14
+
15
+ - Keep controllers focused on HTTP mapping, request binding, validation, and response translation. Delegate business rules and multi-step use cases to an application service.
16
+ - Use dedicated request and response types instead of binding untrusted JSON directly to persistence entities or internal domain state.
17
+ - Validate request bodies and parameters at the boundary. Combine framework validation with domain checks; boundary validation does not replace business invariants.
18
+ - Return appropriate status codes and stable response shapes. Do not expose Java exception names, stack traces, SQL messages, internal paths, or secrets in error responses.
19
+ - Centralize cross-cutting exception-to-response mapping where that keeps behavior consistent. Map known failures deliberately and keep unexpected failures generic to clients while recording safe diagnostic context.
20
+ - Add API contract, serialization, and compatibility checks when clients depend on the endpoint shape.
21
+
22
+ ## Apply Spring Security as the security boundary
23
+
24
+ - Use Spring Security's supported authentication and authorization mechanisms. Do not create a handwritten password store, request filter chain, token verifier, or role check when Spring Security provides the security integration.
25
+ - Define authorization rules for every route and method, starting from deny-by-default or authentication-required behavior and then opening only intentional public endpoints.
26
+ - Enforce authorization close to sensitive operations as well as at the HTTP boundary when the application has non-HTTP entry points. Use the currently supported API for the project's Spring Security version.
27
+ - Preserve CSRF protections for browser sessions unless the threat model and protocol justify a documented alternative. Configure CORS narrowly for known origins and methods; CORS is not authorization.
28
+ - Use secure password storage and vetted identity providers or protocols. Avoid leaking authentication failures, token contents, or user existence through responses and logs.
29
+ - Restrict access to operational endpoints and administration routes. Test both permitted and rejected cases, including unauthenticated and underprivileged callers.
30
+
31
+ ## Keep tests focused on the web contract
32
+
33
+ - Use framework slice tests for the controller or web configuration boundary when possible, and full application tests only when auto-configuration or cross-layer behavior is part of the contract.
34
+ - Exercise validation failures, status codes, content types, response bodies, and security rules. Avoid tests that only assert the controller delegates to a mock.
35
+ - Keep test configuration and credentials isolated. Never use production secrets or shared production data in a test.
36
+
37
+ ## Official references
38
+
39
+ - [Spring Boot servlet web applications](https://docs.spring.io/spring-boot/reference/web/servlet.html)
40
+ - [Spring Framework WebFlux](https://docs.spring.io/spring-framework/reference/web/webflux.html)
41
+ - [Spring MVC validation](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-validation.html)
42
+ - [Spring MVC exception handling](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-exceptionhandler.html)
43
+ - [Spring Security request authorization](https://docs.spring.io/spring-security/reference/servlet/authorization/authorize-http-requests.html)
@@ -24,7 +24,7 @@
24
24
  "augmentMinVersion": "1.0.0",
25
25
  "nodeMinVersion": "18.0.0"
26
26
  },
27
- "characterCount": 302930,
27
+ "characterCount": 304728,
28
28
  "lastUpdated": "2026-11-08",
29
29
  "files": {
30
30
  "rules": [
@@ -23,7 +23,7 @@
23
23
  "augment": {
24
24
  "inject": "on-demand",
25
25
  "priority": "medium",
26
- "characterCount": 302930,
26
+ "characterCount": 304728,
27
27
  "contexts": [
28
28
  "design",
29
29
  "ui",
@@ -38,7 +38,7 @@
38
38
  "desktop"
39
39
  ]
40
40
  },
41
- "characterCount": 302930,
41
+ "characterCount": 304728,
42
42
  "contents": {
43
43
  "core": [
44
44
  "VERSION",
@@ -0,0 +1,67 @@
1
+ # Agent Engineering
2
+
3
+ ## Overview
4
+
5
+ Reusable guidance for creating agents and designing the harness, loop, and graph around them. Start with one task and a check that can reject a bad result. Add machinery only for an observed need. This module supplies static rules and local executable fixtures, not an orchestration service.
6
+
7
+ ## Contents
8
+
9
+ - [Responsibilities and adoption](rules/01-adoption.md)
10
+ - [Agent roles, delegation, and ownership](rules/02-agents.md)
11
+ - [Contracts, evidence, and trust](rules/03-contracts.md)
12
+ - [Bounded loops and recovery](rules/04-loops.md)
13
+ - [Graphs and durable state](rules/05-graphs.md)
14
+ - [Controlled improvement and evaluation](rules/06-improvement.md)
15
+ - [Source review and attribution](sources.md)
16
+ - [Machine-readable schemas](schemas/contracts.schema.json)
17
+ - [Agent](templates/agent.json), [invocation](templates/invocation.json), [task](templates/task.json), [tool](templates/tool.json), [checker tool](templates/check-tool.json), [node](templates/node.json), [evidence](templates/evidence.json), and [state](templates/state.json) templates
18
+ - [Loop controller](examples/loop.cjs), [graph examples](examples/graphs.cjs), [recovery and replay](examples/recovery.cjs), [saved cases](examples/evaluation-cases.json)
19
+ - [Executable demo](examples/demo.cjs) and [module validator](scripts/validate.cjs)
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ augx link workflows/agent-engineering
25
+ augx show workflows/agent-engineering rules/01-adoption.md
26
+ ```
27
+
28
+ Linking loads static guidance. It does not execute examples or change permissions. Use the CLI from a checkout or installed package that contains this module. Existing installed releases will not discover unpublished source changes.
29
+
30
+ ## Usage
31
+
32
+ From this module directory, with Node.js and the package's existing Ajv dependency installed:
33
+
34
+ ```bash
35
+ node scripts/validate.cjs
36
+ node examples/demo.cjs loop repair ./local-repair
37
+ node examples/demo.cjs loop exhaust ./local-exhaust
38
+ node examples/demo.cjs loop stall ./local-stall
39
+ node examples/demo.cjs loop denied ./local-denied
40
+ node examples/demo.cjs loop error ./local-error
41
+ node examples/demo.cjs loop transient ./local-transient
42
+ node examples/demo.cjs loop timeout ./local-timeout
43
+ node examples/demo.cjs graph chain ./local-chain
44
+ node examples/demo.cjs graph router ./local-router
45
+ node examples/demo.cjs graph fan-out ./local-join
46
+ node examples/demo.cjs graph cycle ./local-cycle
47
+ ```
48
+
49
+ Use a new explicitly chosen disposable directory for each scenario. Repeating a command resumes its compatible checkpoint and preserves accounting. Exit 0 means the selected fixture succeeded, 1 means a terminal non-success, and 2 means invalid input, an ownership conflict, incompatible state, or a filesystem failure requiring local inspection. Ctrl+C requests cancellation and kills a running loop subprocess. No external handoff is sent.
50
+
51
+ Example loop defaults are five total attempts, twelve subprocess calls, five seconds including downtime, 750 milliseconds per call, two rounds without improved score, and one worker. The `exhaust` CLI scenario narrows attempts to two to expose exhaustion before stall. The independent checker rejects the first `repair` candidate and accepts the repaired candidate. Check records bind the file bytes, contract, protected code, and caller-supplied revision. The revision is a fixture identity; an adapter must supply the actual repository revision and dirty-candidate digest.
52
+
53
+ The controller owns `state.json`, `receipt.json`, and `handoff.json`; the worker can only return a small candidate for the controller to write to `candidate.json`. Graph examples use `graph-state.json` and `graph-receipt.json`. All joins require every named branch. Fan-out is intentionally executed sequentially, demonstrating the same data contract without native subagents. Branch outputs survive later branch failures for inspection; failed graphs require a reviewed repair plan rather than automatic terminal-state reset.
54
+
55
+ ## Limits and Recovery
56
+
57
+ These are deterministic fixtures, not provider or production evidence. No provider token, request-price, or monetary cap is claimed: no provider is called. Actual adapters must reserve aggregate requests and tokens, reconcile measured usage including failures, and enforce spend externally where possible. Report unknown cost as unknown.
58
+
59
+ There is no OS sandbox. Fixed subprocesses receive no inherited credentials, but a same-user hostile process could alter files or race path checks. Trusted graph handlers must honor cancellation; JavaScript cannot forcibly stop an arbitrary synchronous handler. Use isolated processes or containers with enforced filesystem, network, credential, and process restrictions before executing untrusted code. Full external diagnostics must remain in a separately protected, redacted local artifact; the demo's small typed outputs are its complete diagnostics and are capped at 32 KiB.
60
+
61
+ Atomic checkpoints use a temporary file, fsync, rename, checksum, and an exclusive writer lock. A crash can consume allocation without producing output. Never refund counters automatically. Preserve corrupt checkpoints and incomplete temporary files, inspect the candidate and last durable evidence, then start a new run directory with a reviewed contract. A stale lock is not a lease: inspect its PID, confirm no writer remains, and explicitly remove only that lock after reconciliation. Do not clear locks by age. File fsync and rename are not a promise against every filesystem or power failure.
62
+
63
+ Graph handlers and runtime contracts are version-bound. The scheduler supports DAGs and bounded single-node repair cycles; multi-node cycles need a different scheduler. Callers must version closed-over handler configuration in the revision. For real external effects, use service-supported idempotency or reconcile the service state after a crash. [localEffect](examples/recovery.cjs) demonstrates duplicate-trigger and crash-window reconciliation for a local artifact only. No exactly-once guarantee is made.
64
+
65
+ ## Character Count
66
+
67
+ The loader counts UTF-8-decoded JavaScript string lengths across every module file, including this README, schema, examples, and manifest. `node scripts/validate.cjs --update-count` reconciles the self-inclusive manifest count; plain validation is read-only. Export aggregation reads `rules/`, so example state, templates, source references, and saved evaluation cases are not inserted into native rule surfaces. Keep execution directories outside the module when using it from a checkout.
@@ -0,0 +1,89 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const crypto = require('crypto');
5
+ const Ajv = require('ajv');
6
+ const schema = require('../schemas/contracts.schema.json');
7
+ const ajv = new Ajv({ allErrors: true, strict: true });
8
+ ajv.addSchema(schema, 'contracts');
9
+ const validators = new Map();
10
+ const hash = value => crypto.createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value)).digest('hex');
11
+
12
+ function validate(kind, value) {
13
+ if (!validators.has(kind)) validators.set(kind, ajv.compile({ $ref: `contracts#/definitions/${kind}` }));
14
+ const check = validators.get(kind);
15
+ if (!check(value)) throw new Error(`Invalid ${kind}: ${ajv.errorsText(check.errors)}`);
16
+ for (const name of ['inputSchema', 'outputSchema']) if (value[name]) ajv.compile(value[name]);
17
+ return value;
18
+ }
19
+
20
+ function checkSchema(schemaValue, value) {
21
+ const check = ajv.compile(schemaValue);
22
+ if (!check(value)) throw new Error('Payload does not match schema');
23
+ return value;
24
+ }
25
+
26
+ function safePath(root, relative) {
27
+ if (typeof relative !== 'string' || !/^[a-zA-Z0-9_.\/-]+$/.test(relative) || relative.includes('\\') || path.isAbsolute(relative)) throw new Error('Unsafe path');
28
+ const segments = relative.split('/');
29
+ if (segments.some(s => !s || s === '.' || s === '..' || /[. ]$/.test(s) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(s))) throw new Error('Unsafe path');
30
+ const base = fs.realpathSync(root);
31
+ let current = base;
32
+ for (const segment of segments) {
33
+ current = path.join(current, segment);
34
+ if (fs.existsSync(current) || fs.lstatSync(path.dirname(current)).isSymbolicLink()) {
35
+ if (fs.lstatSync(current).isSymbolicLink()) throw new Error('Symlink path denied');
36
+ const rel = path.relative(base, fs.realpathSync(current));
37
+ if (rel.startsWith('..') || path.isAbsolute(rel)) throw new Error('Path escape');
38
+ }
39
+ }
40
+ return current;
41
+ }
42
+
43
+ function atomic(root, name, value) {
44
+ const destination = safePath(root, name);
45
+ const temporary = safePath(root, `${name}.${crypto.randomBytes(6).toString('hex')}.tmp`);
46
+ const fd = fs.openSync(temporary, 'wx', 0o600);
47
+ try { fs.writeFileSync(fd, JSON.stringify(value, null, 2) + '\n'); fs.fsyncSync(fd); }
48
+ finally { fs.closeSync(fd); }
49
+ fs.renameSync(temporary, destination);
50
+ }
51
+
52
+ function read(root, name) {
53
+ const file = safePath(root, name);
54
+ if (fs.statSync(file).size > 262144) throw new Error('Oversized local state');
55
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
56
+ }
57
+
58
+ function validateTask(task) {
59
+ validate('task', task);
60
+ if (task.writePaths.length !== 1 || task.writePaths[0] !== 'candidate.json' || task.readPaths.some(p => p !== 'candidate.json') || task.requiredChecks.join() !== 'sorted-unique' || task.approvals.length || task.budget.maxWorkers !== 1 || task.budget.maxAttempts > 5 || task.budget.maxCalls > 12 || task.budget.wallMs > 5000 || task.budget.callMs > 750 || task.budget.stallRounds > 2) throw new Error('Reference policy denied task');
61
+ return task;
62
+ }
63
+
64
+ function writeCandidate(root, task, requested, candidate) {
65
+ validateTask(task);
66
+ if (!task.writePaths.includes(requested) || requested !== 'candidate.json') throw new Error('Write permission denied');
67
+ checkSchema({ type: 'array', maxItems: 8, items: { type: 'string', enum: ['a', 'b', 'c'] } }, candidate);
68
+ atomic(root, requested, candidate);
69
+ }
70
+
71
+ function claim(packets, task) {
72
+ validateTask(task);
73
+ const paths = new Set();
74
+ let calls = 0;
75
+ for (const packet of packets) {
76
+ validate('invocation', packet);
77
+ if (packet.task !== task.id || packet.allocation.timeoutMs > task.budget.callMs || packet.tools.some(t => !['stub', 'check'].includes(t))) throw new Error('Delegation permission denied');
78
+ calls += packet.allocation.calls;
79
+ for (const p of packet.writePaths) {
80
+ if (!task.writePaths.includes(p) || paths.has(p.toLowerCase())) throw new Error('Write ownership conflict');
81
+ paths.add(p.toLowerCase());
82
+ }
83
+ }
84
+ if (packets.length > task.budget.maxWorkers) throw new Error('Worker limit exceeded');
85
+ if (calls > task.budget.maxCalls) throw new Error('Shared allocation exceeded');
86
+ return { mode: 'sequential', owners: packets.map(p => p.owner), reservedCalls: calls };
87
+ }
88
+
89
+ module.exports = { validate, checkSchema, hash, safePath, atomic, read, validateTask, writeCandidate, claim };
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+ const path = require('path');
3
+ const { runLoop } = require('./loop.cjs');
4
+ const { exampleGraph, runGraph } = require('./graphs.cjs');
5
+ async function main() {
6
+ const [kind = 'loop', mode = 'repair', destination] = process.argv.slice(2);
7
+ if (!destination) throw new Error('Usage: node examples/demo.cjs <loop|graph> <mode|shape> <explicit-local-directory>');
8
+ const root = path.resolve(destination);
9
+ const controller = new AbortController();
10
+ process.once('SIGINT', () => controller.abort());
11
+ const baseline = require('../templates/task.json');
12
+ const task = mode === 'exhaust' ? { ...baseline, budget: { ...baseline.budget, maxAttempts: 2 } } : baseline;
13
+ const result = kind === 'loop' ? await runLoop({ root, task, mode, signal: controller.signal }) : kind === 'graph' ? await runGraph({ ...exampleGraph(mode), root, signal: controller.signal }) : (() => { throw new Error('Invalid example kind'); })();
14
+ process.stdout.write(JSON.stringify({ outcome: result.status, root, evidence: 'local-deterministic-fixture' }) + '\n');
15
+ process.exitCode = result.status === 'success' ? 0 : 1;
16
+ }
17
+ main().catch(() => { process.stderr.write('Example rejected input or checkpoint; inspect local files without overwriting them.\n'); process.exitCode = 2; });
@@ -0,0 +1,7 @@
1
+ [
2
+ { "candidate": ["a", "b", "c"], "expected": true },
3
+ { "candidate": ["c", "a", "a"], "expected": false },
4
+ { "candidate": [], "expected": false },
5
+ { "candidate": ["a", "b"], "expected": false },
6
+ { "candidate": ["a", "b", "c", "c"], "expected": false }
7
+ ]
@@ -0,0 +1,149 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const { validate, checkSchema, hash, atomic, read, safePath } = require('./contracts.cjs');
4
+
5
+ function validateGraph(graph) {
6
+ validate('graph', graph);
7
+ const ids = new Set(graph.nodes.map(n => n.id));
8
+ if (ids.size !== graph.nodes.length || !ids.has(graph.entry) || !graph.terminals.length || graph.terminals.some(t => !ids.has(t))) throw new Error('Invalid node identifiers');
9
+ for (const n of graph.nodes) {
10
+ // Compile both schemas even if a router never selects this node.
11
+ const Ajv = require('ajv'); const ajv = new Ajv({ strict: true });
12
+ ajv.compile(n.inputSchema); ajv.compile(n.outputSchema);
13
+ if (n.dependencies.some(d => !ids.has(d) || d === n.id) || n.allocation.timeoutMs > 750) throw new Error('Invalid dependencies or allocation');
14
+ if (n.acceptance === 'all-required' && !n.dependencies.length) throw new Error('Join requires explicit branches');
15
+ }
16
+ const seenEdges = new Set();
17
+ for (const e of graph.edges) {
18
+ const key = [e.to, e.artifact, e.condition].join(':');
19
+ if (!ids.has(e.from) || !ids.has(e.to) || seenEdges.has(key)) throw new Error('Invalid or ambiguous edge');
20
+ seenEdges.add(key);
21
+ if (graph.terminals.includes(e.from) || (e.from === e.to && (e.condition === 'always' || graph.nodes.find(n => n.id === e.from).dependencies.length))) throw new Error('Invalid terminal or cycle edge');
22
+ }
23
+ // The reference supports DAGs plus bounded single-node repair cycles.
24
+ const active = new Set(); const complete = new Set();
25
+ const acyclic = id => {
26
+ if (active.has(id)) throw new Error('Multi-node cycles require a different scheduler');
27
+ if (complete.has(id)) return;
28
+ active.add(id);
29
+ for (const e of graph.edges) if (e.from === id && e.to !== id) acyclic(e.to);
30
+ active.delete(id); complete.add(id);
31
+ };
32
+ acyclic(graph.entry);
33
+ const visit = (start, reverse) => {
34
+ const found = new Set(); const queue = [...start];
35
+ while (queue.length) { const id = queue.shift(); if (found.has(id)) continue; found.add(id); for (const e of graph.edges) if ((reverse ? e.to : e.from) === id) queue.push(reverse ? e.from : e.to); }
36
+ return found;
37
+ };
38
+ if (visit([graph.entry], false).size !== ids.size || visit(graph.terminals, true).size !== ids.size) throw new Error('Unreachable node or terminal');
39
+ for (const n of graph.nodes) if (n.dependencies.some(d => !graph.edges.some(e => e.from === d && e.to === n.id))) throw new Error('Join dependency has no artifact edge');
40
+ for (const n of graph.nodes) if (n.id !== graph.entry && (n.inputSchema.required || []).some(key => !graph.edges.some(e => e.to === n.id && e.artifact === key))) throw new Error('Required input has no artifact edge');
41
+ return graph;
42
+ }
43
+
44
+ async function runGraph({ graph, handlers, root, revision = 'fixture-v1', input = { seed: ['c', 'a', 'a', 'b'] }, now = Date.now, signal, pauseAfter = Infinity }) {
45
+ validateGraph(graph);
46
+ if (!root || !handlers || graph.nodes.some(n => typeof handlers[n.id] !== 'function')) throw new Error('Explicit local root and trusted handlers required');
47
+ fs.mkdirSync(root, { recursive: true });
48
+ const lock = safePath(root, 'graph.lock'); const fd = fs.openSync(lock, 'wx');
49
+ try {
50
+ const policy = hash([fs.readFileSync(__filename, 'utf8'), fs.readFileSync(require.resolve('./contracts.cjs'), 'utf8'), fs.readFileSync(require.resolve('../schemas/contracts.schema.json'), 'utf8'), Object.keys(handlers).sort().map(id => [id, handlers[id].toString()])]);
51
+ const contract = hash([graph, input, revision, policy]);
52
+ let s;
53
+ if (fs.existsSync(safePath(root, 'graph-state.json'))) {
54
+ const record = read(root, 'graph-state.json'); s = validate('graphState', record.state);
55
+ if (record.checksum !== hash(s) || s.version !== 1 || s.contract !== contract || s.revision !== revision || !Number.isInteger(s.steps) || s.steps < 0 || s.steps > Math.min(12, graph.maxSteps) || s.deadline !== s.startedAt + 5000 || !['running', 'success', 'error', 'cancelled', 'exhausted'].includes(s.status)) throw new Error('Incompatible graph checkpoint');
56
+ for (const [id, output] of Object.entries(s.outputs)) {
57
+ const node = graph.nodes.find(n => n.id === id);
58
+ if (!node) throw new Error('Unknown checkpoint node');
59
+ checkSchema(node.outputSchema, output);
60
+ if (s.digests[id] !== hash(output)) throw new Error('Stale graph artifact');
61
+ }
62
+ if (s.status === 'success' && (!Object.keys(s.outputs).some(id => graph.terminals.includes(id)) || s.pending.length)) throw new Error('Incomplete graph success');
63
+ } else {
64
+ s = { version: 1, contract, revision, startedAt: now(), deadline: 0, steps: 0, visits: {}, outputs: {}, digests: {}, pending: [{ id: graph.entry, input }], status: 'running', trace: [], reason: 'dispatch' };
65
+ s.deadline = s.startedAt + 5000;
66
+ }
67
+ const persist = () => { validate('graphState', s); atomic(root, 'graph-state.json', { checksum: hash(s), state: s }); };
68
+ let rounds = 0;
69
+ while (s.status === 'running' && s.pending.length && rounds++ < pauseAfter) {
70
+ if (signal?.aborted) { s.status = 'cancelled'; s.reason = 'cancelled'; break; }
71
+ if (now() >= s.deadline || s.steps >= Math.min(12, graph.maxSteps)) { s.status = 'exhausted'; s.reason = 'shared-allocation'; break; }
72
+ const index = s.pending.findIndex(p => graph.nodes.find(n => n.id === p.id)?.dependencies.every(d => Object.hasOwnProperty.call(s.outputs, d)));
73
+ if (index < 0) { s.status = 'error'; s.reason = 'missing-required-branch'; break; }
74
+ const packet = s.pending[index];
75
+ const node = graph.nodes.find(n => n.id === packet.id);
76
+ s.visits[node.id] = (s.visits[node.id] || 0) + 1;
77
+ if (s.visits[node.id] > graph.maxVisits) { s.status = 'exhausted'; s.reason = 'bounded-cycle'; break; }
78
+ s.steps++;
79
+ persist(); // Leave packet pending until its output is durably recorded.
80
+ try {
81
+ checkSchema(node.inputSchema, packet.input);
82
+ const controller = new AbortController();
83
+ const abort = () => controller.abort(); signal?.addEventListener('abort', abort, { once: true });
84
+ let timer;
85
+ let result;
86
+ try {
87
+ result = await Promise.race([
88
+ Promise.resolve().then(() => handlers[node.id](packet.input, { signal: controller.signal, visit: s.visits[node.id] })),
89
+ new Promise((_, reject) => { timer = setTimeout(() => { controller.abort(); reject(new Error('node-timeout')); }, Math.max(1, Math.min(node.allocation.timeoutMs, s.deadline - now()))); controller.signal.addEventListener('abort', () => reject(new Error('cancelled-or-timeout')), { once: true }); })
90
+ ]);
91
+ } finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); }
92
+ if (signal?.aborted) { s.status = 'cancelled'; s.reason = 'cancelled'; break; }
93
+ if (now() >= s.deadline) { s.status = 'exhausted'; s.reason = 'deadline'; break; }
94
+ if (!result || !Object.hasOwnProperty.call(result, 'value') || !['always', 'valid', 'invalid', 'left', 'right'].includes(result.route || 'always')) throw new Error('invalid-route');
95
+ checkSchema(node.outputSchema, result.value);
96
+ s.outputs[node.id] = result.value; s.digests[node.id] = hash(result.value);
97
+ s.pending.splice(index, 1);
98
+ const edges = graph.edges.filter(e => e.from === node.id && (e.condition === 'always' || e.condition === result.route));
99
+ if (!edges.length && !graph.terminals.includes(node.id)) throw new Error('route-has-no-edge');
100
+ for (const edge of edges) {
101
+ let target = s.pending.find(p => p.id === edge.to);
102
+ if (!target) { target = { id: edge.to, input: {} }; s.pending.push(target); }
103
+ target.input[edge.artifact] = result.value;
104
+ }
105
+ s.trace.push({ node: node.id, step: s.steps, contract, artifact: hash(result.value), route: result.route || 'always', elapsedMs: now() - s.startedAt, calls: s.steps, outcome: 'schema-accepted' });
106
+ persist();
107
+ } catch {
108
+ s.status = signal?.aborted ? 'cancelled' : 'error'; s.reason = node.failureRoute === 'handoff' ? 'local-handoff-required' : 'node-rejected';
109
+ }
110
+ }
111
+ if (s.status === 'running' && !s.pending.length) {
112
+ s.status = graph.terminals.some(t => Object.hasOwnProperty.call(s.outputs, t)) ? 'success' : 'error';
113
+ s.reason = s.status === 'success' ? 'selected-terminal-reached' : 'missing-terminal';
114
+ }
115
+ persist();
116
+ if (s.status !== 'running') atomic(root, 'graph-receipt.json', { outcome: s.status, changedArtifacts: ['graph-state.json'], verifiedChecks: ['Schemas and selected transitions'], unverified: ['Provider quality', 'Parallel scheduling', 'OS isolation'], remainingRisk: 'Trusted handlers must honor cancellation; use process isolation for untrusted code', nextOwner: 'controller', nextAction: s.reason, calls: s.steps });
117
+ return s;
118
+ } finally { fs.closeSync(fd); fs.unlinkSync(lock); }
119
+ }
120
+
121
+ function exampleGraph(shape) {
122
+ const list = { type: 'array', items: { type: 'string' }, maxItems: 8 };
123
+ const input = key => ({ type: 'object', additionalProperties: false, properties: { [key]: list }, required: [key] });
124
+ const node = (id, schema, dependencies = []) => ({ id, responsibility: `Produce ${id} artifact`, executor: 'code', inputSchema: schema, outputSchema: list, dependencies, acceptance: dependencies.length ? 'all-required' : 'schema', failureRoute: 'handoff', allocation: { calls: 1, timeoutMs: 100 } });
125
+ const edge = (from, to, artifact, condition = 'always') => ({ from, to, artifact, condition });
126
+ const g = { version: 1, id: shape, entry: 'start', terminals: ['done'], maxSteps: 10, maxVisits: 3, joinPolicy: 'all-required', nodes: [node('start', input('seed'))], edges: [] };
127
+ const handlers = { start: x => ({ value: x.seed }), done: x => ({ value: Object.values(x).flat() }) };
128
+ if (shape === 'chain') {
129
+ g.nodes.push(node('normalize', input('raw')), node('done', input('normalized')));
130
+ g.edges.push(edge('start', 'normalize', 'raw'), edge('normalize', 'done', 'normalized'));
131
+ handlers.normalize = x => ({ value: [...new Set(x.raw)].sort() });
132
+ } else if (shape === 'router') {
133
+ g.terminals = ['left', 'right'];
134
+ g.nodes.push(node('left', input('selected')), node('right', input('selected')));
135
+ g.edges.push(edge('start', 'left', 'selected', 'left'), edge('start', 'right', 'selected', 'right'));
136
+ handlers.start = x => ({ value: x.seed, route: x.seed.length < 5 ? 'left' : 'right' });
137
+ handlers.left = handlers.right = x => ({ value: x.selected });
138
+ } else if (shape === 'fan-out') {
139
+ g.nodes.push(node('left', input('source')), node('right', input('source')), node('done', { type: 'object', additionalProperties: false, properties: { left: list, right: list }, required: ['left', 'right'] }, ['left', 'right']));
140
+ g.edges.push(edge('start', 'left', 'source'), edge('start', 'right', 'source'), edge('left', 'done', 'left'), edge('right', 'done', 'right'));
141
+ handlers.left = x => ({ value: [...new Set(x.source)] }); handlers.right = x => ({ value: [...x.source].sort() });
142
+ } else if (shape === 'cycle') {
143
+ g.nodes.push(node('repair', input('candidate')), node('done', input('checked')));
144
+ g.edges.push(edge('start', 'repair', 'candidate'), edge('repair', 'repair', 'candidate', 'invalid'), edge('repair', 'done', 'checked', 'valid'));
145
+ handlers.repair = (x, context) => ({ value: context.visit === 1 ? x.candidate : [...new Set(x.candidate)].sort(), route: context.visit === 1 ? 'invalid' : 'valid' });
146
+ } else throw new Error('Unknown graph shape');
147
+ return { graph: validateGraph(g), handlers };
148
+ }
149
+ module.exports = { validateGraph, runGraph, exampleGraph };