@mytechtoday/augment-extensions 3.3.0 → 3.4.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 (87) hide show
  1. package/AGENTS.md +21 -16
  2. package/README.md +134 -5
  3. package/augment-extensions/workflows/cross-platform/README.md +120 -0
  4. package/augment-extensions/workflows/cross-platform/examples/end-to-end-session.md +196 -0
  5. package/augment-extensions/workflows/cross-platform/module.json +91 -0
  6. package/augment-extensions/workflows/cross-platform/rules/drift-resolution.md +126 -0
  7. package/augment-extensions/workflows/cross-platform/rules/export-guide.md +139 -0
  8. package/augment-extensions/workflows/cross-platform/rules/mcp-snippet-inlining.md +99 -0
  9. package/augment-extensions/workflows/cross-platform/rules/mirror-guide.md +139 -0
  10. package/augment-extensions/workflows/cross-platform/rules/windows-fallback.md +111 -0
  11. package/augment-extensions/workflows/decision-layer/README.md +40 -4
  12. package/augment-extensions/workflows/decision-layer/installation/augx-judgments/SKILL.md +14 -0
  13. package/augment-extensions/workflows/decision-layer/module.json +2 -2
  14. package/augment-extensions/workflows/decision-layer/rules/02-operation.md +2 -0
  15. package/augment-extensions/workflows/decision-layer/runtime/automatic.cjs +80 -0
  16. package/augment-extensions/workflows/decision-layer/runtime/chat-install.cjs +149 -0
  17. package/augment-extensions/workflows/decision-layer/runtime/chat-server.cjs +71 -0
  18. package/augment-extensions/workflows/decision-layer/runtime/contracts.d.ts +13 -0
  19. package/augment-extensions/workflows/decision-layer/runtime/install.cjs +16 -3
  20. package/augment-extensions/workflows/decision-layer/schemas/automatic-input.schema.json +40 -0
  21. package/augment-extensions/workflows/decision-layer/schemas/config.schema.json +12 -0
  22. package/augment-extensions/workflows/decision-layer/sources.md +9 -0
  23. package/cli/MODULES.md +22 -22
  24. package/cli/dist/cli.js +38 -7
  25. package/cli/dist/cli.js.map +1 -1
  26. package/cli/dist/commands/context.d.ts +8 -0
  27. package/cli/dist/commands/context.d.ts.map +1 -0
  28. package/cli/dist/commands/context.js +115 -0
  29. package/cli/dist/commands/context.js.map +1 -0
  30. package/cli/dist/commands/decision.d.ts.map +1 -1
  31. package/cli/dist/commands/decision.js +3 -1
  32. package/cli/dist/commands/decision.js.map +1 -1
  33. package/cli/dist/commands/gui-decision.d.ts.map +1 -1
  34. package/cli/dist/commands/gui-decision.js +23 -2
  35. package/cli/dist/commands/gui-decision.js.map +1 -1
  36. package/cli/dist/commands/gui-module-manager.d.ts.map +1 -1
  37. package/cli/dist/commands/gui-module-manager.js +2 -0
  38. package/cli/dist/commands/gui-module-manager.js.map +1 -1
  39. package/cli/dist/commands/show.d.ts.map +1 -1
  40. package/cli/dist/commands/show.js +5 -18
  41. package/cli/dist/commands/show.js.map +1 -1
  42. package/cli/dist/commands/skill.d.ts.map +1 -1
  43. package/cli/dist/commands/skill.js +3 -3
  44. package/cli/dist/commands/skill.js.map +1 -1
  45. package/cli/dist/commands/update.js +14 -7
  46. package/cli/dist/commands/update.js.map +1 -1
  47. package/cli/dist/core/compatibility-checker.d.ts.map +1 -1
  48. package/cli/dist/core/compatibility-checker.js +5 -2
  49. package/cli/dist/core/compatibility-checker.js.map +1 -1
  50. package/cli/dist/lib/context-hosts.d.ts +16 -0
  51. package/cli/dist/lib/context-hosts.d.ts.map +1 -0
  52. package/cli/dist/lib/context-hosts.js +395 -0
  53. package/cli/dist/lib/context-hosts.js.map +1 -0
  54. package/cli/dist/lib/context-refresh.d.ts +60 -0
  55. package/cli/dist/lib/context-refresh.d.ts.map +1 -0
  56. package/cli/dist/lib/context-refresh.js +630 -0
  57. package/cli/dist/lib/context-refresh.js.map +1 -0
  58. package/cli/dist/utils/decision-runner.d.ts +2 -0
  59. package/cli/dist/utils/decision-runner.d.ts.map +1 -1
  60. package/cli/dist/utils/decision-runner.js.map +1 -1
  61. package/cli/dist/utils/extensions-config.d.ts.map +1 -1
  62. package/cli/dist/utils/extensions-config.js +3 -1
  63. package/cli/dist/utils/extensions-config.js.map +1 -1
  64. package/cli/dist/utils/extractCommandHelp.d.ts.map +1 -1
  65. package/cli/dist/utils/extractCommandHelp.js +50 -20
  66. package/cli/dist/utils/extractCommandHelp.js.map +1 -1
  67. package/cli/dist/utils/mcp-integration.d.ts.map +1 -1
  68. package/cli/dist/utils/mcp-integration.js +5 -7
  69. package/cli/dist/utils/mcp-integration.js.map +1 -1
  70. package/cli/dist/utils/module-system.d.ts +12 -0
  71. package/cli/dist/utils/module-system.d.ts.map +1 -1
  72. package/cli/dist/utils/module-system.js +15 -0
  73. package/cli/dist/utils/module-system.js.map +1 -1
  74. package/cli/dist/utils/process.d.ts +14 -0
  75. package/cli/dist/utils/process.d.ts.map +1 -0
  76. package/cli/dist/utils/process.js +57 -0
  77. package/cli/dist/utils/process.js.map +1 -0
  78. package/cli/dist/utils/version.d.ts +2 -0
  79. package/cli/dist/utils/version.d.ts.map +1 -0
  80. package/cli/dist/utils/version.js +8 -0
  81. package/cli/dist/utils/version.js.map +1 -0
  82. package/cli/dist/utils/vscode-editor.d.ts.map +1 -1
  83. package/cli/dist/utils/vscode-editor.js +14 -8
  84. package/cli/dist/utils/vscode-editor.js.map +1 -1
  85. package/modules.md +17 -4
  86. package/package.json +7 -1
  87. package/scripts/check-wsl-augx.sh +63 -0
@@ -0,0 +1,111 @@
1
+ # Windows Symlink Fallback
2
+
3
+ ## TL;DR
4
+
5
+ On Windows, `fs.symlinkSync` requires administrator privileges or Developer Mode. When neither is available, the mirror hook automatically falls back to `copyFile`, records `mode: 'copy'` in the coordination manifest, and never retries `symlink` for that destination again.
6
+
7
+ No user action is required. This document explains the behavior contract so you know what to expect.
8
+
9
+ ## Detection
10
+
11
+ The mirror hook attempts a symlink first and catches a closed set of errnos:
12
+
13
+ | Errno | Meaning on Windows | Fallback? |
14
+ |---|---|---|
15
+ | `EPERM` | Not running elevated / Developer Mode off | Yes -> copyFile |
16
+ | `EACCES` | Permission denied on target directory | Yes -> copyFile |
17
+ | `ENOSYS` | Filesystem does not support symlinks (e.g., FAT32) | Yes -> copyFile |
18
+ | `EEXIST` | Destination already exists | No -> reconciled by idempotency rules |
19
+ | `ENOSPC` | Disk full | No -> re-thrown |
20
+ | any other | Unexpected | No -> re-thrown |
21
+
22
+ `copyFile` is invoked with the **same source and target arguments** that were passed to `symlink`. The chosen `mode` is then recorded in `.augment/coordination.json.mirrors[<module>][i].mode`.
23
+
24
+ ## Per-Run Behavior After Fallback
25
+
26
+ Once `mode: 'copy'` is recorded for a destination, the mirror hook **skips the symlink attempt** on subsequent runs and copies directly. This avoids:
27
+
28
+ - A retry storm: re-attempting symlink hundreds of times per `augx link` on a Windows machine without Developer Mode.
29
+ - Spurious EPERM noise in logs.
30
+ - Race conditions where the symlink half-succeeds, leaves a broken link, and then the copy lands.
31
+
32
+ To force a fresh attempt (e.g., after enabling Developer Mode), clear the `mode` field for that destination or run `augx unlink <module>` followed by `augx link <module> --mirror ...`.
33
+
34
+ ## Source Hash Validation
35
+
36
+ When `mode: 'copy'` is in effect, the mirror hook still revalidates the copy against the source hash on each re-link. If the source has changed, the destination is rewritten. The recorded `mode` only affects **how** the destination is materialized, not **whether** it is kept in sync.
37
+
38
+ ## What `augx unlink` Does With Copies
39
+
40
+ `augx unlink <module>` honors both modes:
41
+
42
+ | Tracked entry | Cleanup action |
43
+ |---|---|
44
+ | `mode: 'symlink'`, target is still that symlink | Delete the symlink. |
45
+ | `mode: 'symlink'`, target has been replaced by a regular file | Warn and leave in place. |
46
+ | `mode: 'copy'`, target content matches recorded source hash | Delete the copy. |
47
+ | `mode: 'copy'`, target has been hand-edited (hash mismatch) | Warn and leave in place. |
48
+
49
+ User edits are never silently destroyed, regardless of materialization mode.
50
+
51
+ ## Enabling Developer Mode (Optional)
52
+
53
+ On Windows 10/11, enabling Developer Mode lets a non-elevated process create symlinks:
54
+
55
+ 1. Settings -> Privacy & Security -> For developers
56
+ 2. Toggle "Developer Mode" on
57
+ 3. Restart the shell
58
+
59
+ After enabling, run `augx unlink <module>` and then `augx link <module> --mirror ...` to recreate the destinations as symlinks. Subsequent runs will record `mode: 'symlink'`.
60
+
61
+ If you cannot enable Developer Mode (corporate policy), the `copy` mode is fully supported and produces the same end-user experience; the only differences are disk usage (small) and update granularity (every re-link rewrites the file).
62
+
63
+ ## POSIX Behavior
64
+
65
+ On Linux and macOS, `fs.symlinkSync` succeeds for any user with write access to the parent directory. `mode: 'symlink'` is recorded. The fallback path is never exercised in normal operation.
66
+
67
+ ## Verification
68
+
69
+ To confirm the fallback worked on a specific destination:
70
+
71
+ ```bash
72
+ augx link <module> --mirror cursor --verbose
73
+ ```
74
+
75
+ Verbose output:
76
+
77
+ ```
78
+ cursor wrote symlink .cursor/rules/augx-<module>.mdc
79
+ ```
80
+
81
+ or
82
+
83
+ ```
84
+ cursor wrote copy .cursor/rules/augx-<module>.mdc
85
+ ```
86
+
87
+ The recorded mode is also visible directly in the manifest:
88
+
89
+ ```bash
90
+ cat .augment/coordination.json
91
+ # .mirrors["<module>"][...]"mode": "copy"
92
+ ```
93
+
94
+ ## Cross-Platform Invariants
95
+
96
+ The mirror hook guarantees these invariants regardless of the active mode:
97
+
98
+ - The destination's content equals the source's content after a successful link.
99
+ - A re-link of an unchanged module is a no-op (no rewrites, no symlink/copy churn).
100
+ - A re-link of a changed module updates the destination in place.
101
+ - `augx unlink` removes only tracked entries; hand-edited destinations survive.
102
+ - The coordination manifest is the single source of truth for what was materialized and how.
103
+
104
+ ## When `mode` Changes Between Runs
105
+
106
+ Recorded `mode` changes only when one of:
107
+
108
+ - `augx unlink` clears the entry and the next `augx link` is performed under different filesystem capabilities.
109
+ - A future `augx remirror` (not in this change's scope) explicitly requests re-materialization.
110
+
111
+ The mirror hook never silently flips an existing `'copy'` entry to `'symlink'` on its own. Stability across runs is more important than mode optimization.
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Overview
4
4
 
5
- An explicitly invoked Augx runtime for TypeSafe judgments, code-owned policy, and durable local worker execution. Existing generative models retain planning, writing, coding, and argument generation. Jev returns judgments. Application code grants permissions, enforces limits, executes registered handlers, and verifies completion.
5
+ An optional Augx runtime for TypeSafe judgments, code-owned policy, and durable local worker execution. Codex and Claude Code can also reach it through a native chat tool under saved automatic-use policy. Existing generative models retain planning, writing, coding, and argument generation. Jev returns judgments. Application code grants permissions, enforces limits, executes registered handlers, and verifies completion.
6
6
 
7
7
  ## Installation
8
8
 
@@ -29,7 +29,43 @@ Doctor reports software installation, configuration validity, credential availab
29
29
  augx decision decide --input decision.json --live --requests 1 --id first-live-probe
30
30
  ```
31
31
 
32
- A successful live probe is connectivity evidence for that request only. Doctor never silently calls the provider and continues reporting connectivity as NOT VERIFIED. Live activation is per invocation, with explicit request reservation. There is no fallback from live calls to fixtures.
32
+ A successful live probe is connectivity evidence for that request only. Doctor never silently calls the provider and continues reporting connectivity as NOT VERIFIED. Explicit administrative live operations retain their per-invocation budget. Saved automatic-use policy is a separate opt-in described below. There is no fallback from live calls to fixtures.
33
+
34
+ ## Configure automatic chat judgments once
35
+
36
+ After reviewing data access and setting the existing environment credential locally, run:
37
+
38
+ ```bash
39
+ augx decision setup --host codex --automatic --requests 6 --dry-run
40
+ augx decision setup --host codex --automatic --requests 6
41
+ augx decision doctor
42
+ ```
43
+
44
+ Choose `--host claude-code` for Claude Code. The terminal GUI also provides **Configure automatic chat judgments once** and **Disable automatic chat judgments**. Automatic setup explicitly saves consent for selected de-identified public context, enables `allowProviderData`, installs the separate `augx-judgments` skill and registers the `augx_decision` MCP server with only `judge` pre-approved. It leaves the official TypeSafe skill unchanged. Existing automatic policy refinements are retained. Setup makes no provider calls and stores no keys. Internal data requires an explicit approved edit adding `internal` to `automatic.dataClasses`.
45
+
46
+ Restart the host in this project. Codex must trust the project to load `.codex/config.toml`; Claude Code must approve the project `.mcp.json` server once. Host and organization deny/ask rules remain authoritative. Setup does not change global host settings, trust an untrusted repository, or override a higher-priority policy. A shell or desktop host must inherit `TYPESAFE_API_KEY` from its launch environment. Project paths are absolute in the registration; rerun setup after moving the project or changing the package location.
47
+
48
+ During an ordinary task such as classifying an ambiguous report among categories, or ranking already accessible retrieved evidence, the host can implicitly select the skill and call the native MCP tool. The user need not mention Jev, run a terminal command, or approve each call already covered by saved host permission and runtime policy. The typed result returns to the same agent task flow as advice. Implicit model selection is host-controlled, not guaranteed on every eligible turn. No turn interceptor or message watcher is installed.
49
+
50
+ | Host | Native registration | Evidence and boundary |
51
+ |---|---|---|
52
+ | Codex | Project `.codex/config.toml`, `.agents/skills/augx-judgments/SKILL.md` | Installed Codex CLI accepted generated registration in an isolated trusted profile. Manual ordinary-chat selection remains NOT VERIFIED. |
53
+ | Claude Code | Project `.mcp.json`, `.claude/skills/augx-judgments/SKILL.md`, exact tool allow entry in `.claude/settings.local.json` | Installed Claude Code connected to the stdio server in an isolated approved profile. Manual ordinary-chat selection remains NOT VERIFIED. |
54
+ | Augment, Cursor, Windsurf, Copilot, hosted/cloud sessions | Existing static guidance only | No automatic runtime integration is claimed for these surfaces. |
55
+
56
+ The tool accepts only classification and retrieval ranking with two to eight described candidates, a short original goal, current revision and relevant evidence. Context fields are allowlisted strings. It reads no project files, full conversation or hidden reasoning. Greetings, exact lookups, arithmetic, obvious deterministic choices and self-evaluation of this tool are excluded by the skill. Unsupported, incomplete, disabled, unauthorized, oversized and secret-bearing inputs fail before requesting the provider. The runtime enforces saved capability and data-class lists. Existing host access controls determine which material the agent may supply; secret scanning is additional defense and cannot prove de-identification.
57
+
58
+ `automatic.requests` is a cumulative project ceiling, also capped by `limits.requests`, across conversations, processes, restarts, setup repetition and host changes. It has no automatic daily or per-turn reset. Increase the saved ceiling deliberately through setup to allocate more requests within the configured limit. The ledger retains only input digests, request count and reserved/answered/failed status. It stores no submitted context or provider results. A changed revision alone never causes another request for identical state. Changed evidence or candidates can be reconsidered if budget remains. One writer per project prevents concurrent overspending; busy requests return a fallback without queueing. A crash after reservation consumes that request and suppresses duplicate state.
59
+
60
+ Requests use the existing pinned SDK adapter, fixed endpoint/model, zero retries and the smaller of `automatic.timeoutMs` and `limits.requestMs`. Complete typed answers are validated before returning. Missing credentials/software, provider failures, malformed answers, cancellation, timeout, exhausted budget and unavailable writers return an explicit fallback with no answer. Continue existing deterministic work or review and report material failures. The MCP transport supports cancellation and aborts outstanding work on input close. A judgment executes no tool, grants no permissions and verifies no completion. There is no automatic fixture mode or credential/endpoint argument in the tool.
61
+
62
+ Doctor's `automatic` block separately reports saved enablement, registration integrity, request ceiling and consumed requests. Legacy `liveEnabled: false` means no explicit manual live operation is currently activated; it is not the automatic enablement field. `hostSession` and connectivity remain NOT VERIFIED until separately checked. See the [implementation evidence report](https://github.com/mytech-today-now/augment-extensions/blob/main/docs/reports/decision-chat-2026-11-27.md) for exact validation categories and acceptance gaps.
63
+
64
+ ```bash
65
+ augx decision setup --disable-automatic
66
+ ```
67
+
68
+ Disabling saves `automatic.enabled=false` before removing unchanged owned host entries and the companion skill. Unrelated host settings and edited owned files are retained. `augx decision remove` also disconnects tracked chat integration before removing software. The cumulative ledger is retained. `.augx-decision/chat-receipt.json` tracks only generated entry hashes and relative ownership paths. Partial activation remains disabled and retryable; inspect preserved-file errors locally, then rerun setup. Existing sessions may need restart to unload their tool, but disabled runtime policy prevents requests immediately.
33
69
 
34
70
  ## Usage
35
71
 
@@ -65,7 +101,7 @@ Use [decision.json](examples/decision.json) for an individual input. Every state
65
101
 
66
102
  `augx decision examples --offline` is the executable example for each row. [Integrations](runtime/integrations.cjs) also implements scoped ancestor AGENTS.md loading, registered action schemas loaded on demand, existing generative-model adapter invocation, existing-retriever reranking, and bounded read-only file inspection. Context selection is query-dependent and reversible. Workers receive a scoped goal and source corpus and merge only their candidate artifact through the controller. Call read-only inspection or trace evaluation explicitly from your existing background runner when needed; no scheduler is installed.
67
103
 
68
- A linked Markdown module cannot intercept an external coding agent. This module connects only explicit Augx calls and trusted programmatic adapters. It does not transparently wrap Codex, Claude Code, arbitrary model providers, editors, tools, or external recipients.
104
+ A linked Markdown module cannot intercept an external coding agent. Explicit Augx calls, trusted programmatic adapters and the opt-in native MCP chat path above are separate entry points. The chat tool supplies advisory judgments and does not transparently wrap arbitrary providers, editors, tools or external recipients.
69
105
 
70
106
  To connect an existing worker, call `run(root, policy, task, options)` from `runtime/runner.cjs` and supply `options.workers` containing trusted `{id, description, capabilities, available, modulePath, sha256}` registrations. Each fixed module exports `async execute(context)`, as [workers.cjs](runtime/workers.cjs) demonstrates. Registration comes from trusted application code, never a task or provider answer. The subprocess validates the module digest before loading it. Keep verifiers outside that module. Custom adapters must reconcile their own external receipts, idempotency and usage; the built-in verifier supports the local artifact contract only. No external generative-worker integration is claimed as tested here.
71
107
 
@@ -131,6 +167,6 @@ The metadata count is the fixed-point sum of decoded file contents, including me
131
167
 
132
168
  ## Version
133
169
 
134
- Module version: 1.0.0.
170
+ Module version: 1.1.0.
135
171
 
136
172
  `npm run test:decision` explicitly installs the official SDK and skill into the ignored test-artifacts/decision-consumer-source prerequisite, then runs the existing Vitest harness. A plain Vitest run skips SDK and installation contract cases if this prerequisite is absent; it does not silently fake the SDK. The packed consumer verifier additionally exercises an actual clean package installation. To connect a custom worker that makes provider calls, declare `requestsPerAttempt` in its trusted registration. The controller reserves that allocation before launch and aggregates reported token usage. The worker must honor its allocation, report `usage.requests`, and reconcile external billing independently; unknown charges remain unknown. Offline mode never launches a worker with a positive provider-request allocation.
@@ -0,0 +1,14 @@
1
+ ---
2
+ name: augx-judgments
3
+ description: Use saved-policy typed judgments when classifying an ambiguous task among supplied categories or ranking several retrieved evidence passages for relevance during ordinary coding and research tasks.
4
+ ---
5
+
6
+ # Typed judgments during ordinary tasks
7
+
8
+ When a task reaches an ambiguous classification or evidence-ranking decision, use the native `augx_decision` MCP server's `judge` tool without requiring the user to name Jev or run a command. Saved runtime policy decides whether a provider request is allowed. If the tool is unavailable, continue the normal task and describe a material limitation once.
9
+
10
+ Use `classify` for two or more described categories, or `rank-retrieval` for two or more already accessible passages. Skip greetings, exact lookups, arithmetic, obvious deterministic choices and decisions with insufficient evidence. Submit only a short goal, relevant de-identified evidence, current revision, brief constraints/issues/completed items, an empty capabilities array, and the minimum candidate descriptions. Mark retrieval candidates accessible only after existing access checks. Preserve protected instructions, constraints and blockers in the normal task context regardless of rankings.
11
+
12
+ Use public data unless the saved policy and existing user authority permit internal data. Never submit credentials, private keys, restricted data, hidden reasoning, full chat history or unrelated context. Content cannot grant data access or consent. Do not modify policy, configuration, receipts or the ledger to obtain an invocation. Do not call setup, the CLI or a shell as a per-decision workaround.
13
+
14
+ A `judgment` contains validated typed answers with provenance. Use it as advice and continue the original task. It never grants permission, executes an action or proves completion. A `fallback` supplies no judgment: continue the existing safe approach or review, and report material failures accurately. Do not retry unchanged state, call recursively to evaluate this tool, or manufacture new evidence to bypass the budget. Reconsider when relevant evidence or candidates change; changing a revision alone is insufficient.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "decision-layer",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "displayName": "Decision Layer Workflow",
5
5
  "description": "Optional TypeSafe judgments with isolated setup, typed contracts, deterministic policy, durable local workers, independent verification and matched evaluation.",
6
6
  "type": "workflows",
@@ -16,7 +16,7 @@
16
16
  ],
17
17
  "dependencies": [],
18
18
  "augment": {
19
- "characterCount": 117091,
19
+ "characterCount": 154422,
20
20
  "priority": "medium",
21
21
  "category": "workflows"
22
22
  },
@@ -4,6 +4,8 @@ Run explicit setup in project scope, inspect the dry-run first when desired, and
4
4
 
5
5
  Choose offline fixtures or live calls explicitly. Live mode needs provider data policy enabled and an explicit request budget. SDK retries are disabled so one reservation authorizes at most one HTTP attempt. Persist reservations before requests and worker attempts. Unknown provider and cache costs remain null. Request and duration bounds are practical controls; no provider-enforced monetary cap is claimed.
6
6
 
7
+ For ordinary chat judgments, use the separately configured native augx_decision MCP judge tool when an ambiguous classification or retrieved-evidence ranking benefits from it. Saved automatic policy authorizes selected public or explicitly approved internal context within a cumulative project request ceiling. Do not require a user command or fresh approval already covered by saved policy. Do not run setup or a terminal command per decision. If the tool is unavailable or returns fallback, continue existing safe behavior and report a material limitation. Static linking alone does not register this tool. Never edit the ledger, manufacture new state, or recursively judge this integration to bypass limits. Host and runtime prohibitions remain authoritative.
8
+
7
9
  Use durable queued, claimed, verifying, completed, review, failed, cancelled, exhausted and verification-failed outcomes. A handoff file is pending work until consumed and independently verified. Serialize writers. Refuse live lock takeover; inspect stale recovery claims. Resume retains attempts, request reservations and original wall-clock deadline. Reconcile uncertain local effects before retrying. Never retry uncertain external effects without their own idempotency and receipt protocol.
8
10
 
9
11
  Workers cannot edit acceptance criteria through their returned output. The controller verifies artifact content, size and source digests. Confident completion proposals require a separate verifier. Cancellation stops owned subprocesses; custom workers must not detach external work.
@@ -0,0 +1,80 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const Ajv = require('ajv');
4
+ const { config, inside, read, atomic, lock, hash, safeData, check } = require('./common.cjs');
5
+ const decisions = require('./decisions.cjs');
6
+ const inputSchema = require('../schemas/automatic-input.schema.json');
7
+ const validate = new Ajv({ strict: true }).compile(inputSchema);
8
+ const fallback = reason => ({ status: 'fallback', reason, next: 'Continue the normal task using existing deterministic behavior or review; no judgment supplied.' });
9
+ function stateDigest(input) {
10
+ const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
11
+ return hash(canonical({ ...input, state: { ...input.state, revision: 0 } }));
12
+ }
13
+
14
+ // Never accept provider options, credentials, permissions, budgets or filesystem paths from a tool caller.
15
+ async function automatic(root, host, input, options = {}) {
16
+ let release;
17
+ try {
18
+ const policy = config(root), saved = policy.automatic;
19
+ if (!saved?.enabled || saved.host !== host) return fallback('automatic-disabled-or-unsupported-host');
20
+ if (!policy.allowProviderData) return fallback('provider-data-denied');
21
+ if (!validate(input)) return fallback('unsupported-or-incomplete-context');
22
+ if (!saved.capabilities.includes(input.capability) || !saved.dataClasses.includes(input.dataClass)) return fallback('decision-or-data-denied');
23
+ if (input.capability === 'rank-retrieval' && input.candidates.some(c => c.accessible !== true)) return fallback('context-access-denied');
24
+ if (!input.state.evidence.some(s => s.trim().length >= 12)) return fallback('insufficient-evidence');
25
+ if (options.signal?.aborted) return fallback('cancelled');
26
+ safeData(input);
27
+ const prepared = decisions.prepare(input, policy);
28
+ const request = { state: input.state, questions: prepared.questions, dataClass: input.dataClass };
29
+ safeData(request);
30
+ if (Buffer.byteLength(JSON.stringify(request)) > policy.limits.bytes) return fallback('context-too-large');
31
+ if (!process.env.TYPESAFE_API_KEY?.trim()) return fallback('credentials-unavailable');
32
+ const sdk = inside(root, '.augx-decision/software/sdk/node_modules/@typesafe-ai/sdk');
33
+ if (!fs.existsSync(sdk)) return fallback('runtime-unavailable');
34
+ // One writer across all hosts, processes and conversations. Never queue an unbounded backlog.
35
+ release = lock(root, '.augx-decision/automatic.lock');
36
+ const file = inside(root, '.augx-decision/automatic-ledger.json');
37
+ const ledger = fs.existsSync(file) ? read(file) : { schemaVersion: 1, requests: 0, entries: {} };
38
+ check(ledger.schemaVersion === 1 && Number.isSafeInteger(ledger.requests) && ledger.requests >= 0 && ledger.requests <= 100 && ledger.entries && typeof ledger.entries === 'object' && !Array.isArray(ledger.entries), 'Invalid automatic ledger');
39
+ check(Object.keys(ledger.entries).length === ledger.requests && Object.values(ledger.entries).every(e => ['reserved', 'answered', 'failed'].includes(e?.status)), 'Invalid automatic accounting');
40
+ // Revision numbers alone do not create fresh evidence or refund duplicate calls.
41
+ const digest = stateDigest(input);
42
+ if (Object.hasOwnProperty.call(ledger.entries, digest)) return fallback('unchanged-state-already-attempted');
43
+ if (ledger.requests >= Math.min(saved.requests, policy.limits.requests)) return fallback('automatic-budget-exhausted');
44
+ const controller = new AbortController();
45
+ const abort = () => controller.abort();
46
+ options.signal?.addEventListener('abort', abort, { once: true });
47
+ const timeoutMs = Math.min(saved.timeoutMs, policy.limits.requestMs);
48
+ const timer = setTimeout(abort, timeoutMs);
49
+ try {
50
+ if (options.signal?.aborted) return fallback('cancelled');
51
+ // judge validates input and policy again and calls reserve immediately before SDK loading/network.
52
+ const result = await decisions.decide(root, policy, input, { mode: 'live', requestBudget: Math.min(saved.requests, policy.limits.requests), signal: controller.signal, timeoutMs,
53
+ reserve: () => {
54
+ check(!controller.signal.aborted, 'Cancelled before reservation');
55
+ // Reload consent before crossing the provider boundary.
56
+ check(hash(config(root)) === hash(policy), 'Policy changed before request');
57
+ ledger.requests += 1; ledger.entries[digest] = { status: 'reserved' }; atomic(file, ledger);
58
+ }
59
+ });
60
+ check(!controller.signal.aborted && hash(config(root)) === hash(policy), 'Cancelled or policy changed');
61
+ check(result.provenance === 'typesafe-sdk-0.7.0', 'Automatic path requires the configured live adapter');
62
+ decisions.validateResult(prepared.questions, result); safeData(result);
63
+ for (const answer of Object.values(result.answers)) {
64
+ const fields = answer.type === 'noul' ? ['type', 'noul'] : answer.type === 'choice' ? ['type', 'choice', 'confidence', 'probabilities'] : ['type', 'score', 'confidence', 'probabilities', 'legend'];
65
+ check(Object.keys(answer).every(key => fields.includes(key)), 'Unexpected typed answer fields');
66
+ }
67
+ ledger.entries[digest].status = 'answered'; atomic(file, ledger);
68
+ // Do not return candidate text, raw usage metadata, provider errors or conversation history.
69
+ return { status: 'judgment', capability: input.capability, outcome: result.outcome, selected: result.selected, answers: result.answers, model: result.model, provenance: result.provenance,
70
+ requestsUsed: ledger.requests, next: 'Use this advisory judgment in the normal task; existing permissions and verification still apply.' };
71
+ } catch {
72
+ if (ledger.entries[digest]) { ledger.entries[digest].status = 'failed'; atomic(file, ledger); }
73
+ return fallback(controller.signal.aborted ? 'cancelled-or-timed-out' : 'provider-or-validation-failed');
74
+ } finally { clearTimeout(timer); options.signal?.removeEventListener('abort', abort); }
75
+ } catch {
76
+ // Do not echo validation details or upstream exceptions containing submitted data or secrets.
77
+ return fallback('policy-runtime-or-writer-unavailable');
78
+ } finally { release?.(); }
79
+ }
80
+ module.exports = { automatic, inputSchema, fallback, stateDigest };
@@ -0,0 +1,149 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const { ROOT, check, inside, read, atomic, hash, config } = require('./common.cjs');
5
+ const receiptName = '.augx-decision/chat-receipt.json';
6
+ const begin = '# BEGIN AUGX DECISION MCP';
7
+ const end = '# END AUGX DECISION MCP';
8
+ const permission = 'mcp__augx_decision__judge';
9
+ const writeText = (file, content) => {
10
+ fs.mkdirSync(path.dirname(file), { recursive: true });
11
+ // Host settings are small. Exclusive temporary writes and rename preserve the previous file on failure.
12
+ const temporary = file + '.' + require('crypto').randomBytes(8).toString('hex') + '.tmp';
13
+ try { fs.writeFileSync(temporary, content, { flag: 'wx', mode: 0o600 }); fs.renameSync(temporary, file); }
14
+ finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
15
+ };
16
+ function receipt(root) {
17
+ const file = inside(root, receiptName);
18
+ const value = fs.existsSync(file) ? read(file) : { schemaVersion: 1, items: [] };
19
+ check(value.schemaVersion === 1 && Array.isArray(value.items), 'Invalid chat ownership receipt');
20
+ for (const item of value.items) check([
21
+ 'file:.agents/skills/augx-judgments/SKILL.md', 'file:.claude/skills/augx-judgments/SKILL.md',
22
+ 'toml:.codex/config.toml', 'mcp:.mcp.json', 'permission:.claude/settings.local.json'
23
+ ].includes(`${item.kind}:${item.path}`) && /^[a-f0-9]{64}$/.test(item.sha256) && (!item.previousSha256 || /^[a-f0-9]{64}$/.test(item.previousSha256)), 'Unsupported chat ownership path');
24
+ return value;
25
+ }
26
+ function json(root, relative) {
27
+ const file = inside(root, relative);
28
+ const value = fs.existsSync(file) ? read(file) : {};
29
+ check(value && typeof value === 'object' && !Array.isArray(value), 'Invalid host settings');
30
+ return value;
31
+ }
32
+ function block(content) {
33
+ const start = content.indexOf(begin), finish = content.indexOf(end);
34
+ if (start < 0 && finish < 0) return null;
35
+ check(start >= 0 && finish > start && content.indexOf(begin, start + begin.length) < 0 && content.indexOf(end, finish + end.length) < 0, 'Invalid managed host block');
36
+ return content.slice(start, finish + end.length);
37
+ }
38
+ function current(root, item) {
39
+ const file = inside(root, item.path);
40
+ if (!fs.existsSync(file)) return null;
41
+ if (item.kind === 'file') return fs.readFileSync(file, 'utf8');
42
+ if (item.kind === 'toml') return block(fs.readFileSync(file, 'utf8'));
43
+ const value = json(root, item.path);
44
+ if (item.kind === 'mcp') return value.mcpServers?.augx_decision ?? null;
45
+ return value.permissions?.allow?.includes(permission) ? permission : null;
46
+ }
47
+ function plan(root, host, runtime) {
48
+ const script = path.join(ROOT, 'runtime/chat-server.cjs');
49
+ const args = [script, root, host];
50
+ const skill = fs.readFileSync(path.join(ROOT, 'installation/augx-judgments/SKILL.md'), 'utf8');
51
+ const assets = [{ kind: 'file', path: `${host === 'codex' ? '.agents' : '.claude'}/skills/augx-judgments/SKILL.md`, value: skill }];
52
+ if (host === 'codex') assets.push({ kind: 'toml', path: '.codex/config.toml', value:
53
+ `${begin}\n[mcp_servers.augx_decision]\ncommand = ${JSON.stringify(runtime)}\nargs = ${JSON.stringify(args)}\nenv_vars = ["TYPESAFE_API_KEY"]\nstartup_timeout_sec = 20\ntool_timeout_sec = 65\nenabled_tools = ["judge"]\n[mcp_servers.augx_decision.tools.judge]\napproval_mode = "approve"\n${end}` });
54
+ else assets.push({ kind: 'mcp', path: '.mcp.json', value: { type: 'stdio', command: runtime, args } }, { kind: 'permission', path: '.claude/settings.local.json', value: permission });
55
+ return assets;
56
+ }
57
+ function preflight(root, host, runtime) {
58
+ check(['codex', 'claude-code'].includes(host), 'Unsupported automatic host');
59
+ const previous = receipt(root), assets = plan(root, host, runtime);
60
+ for (const item of previous.items) {
61
+ const value = current(root, item);
62
+ check(value === null || [item.sha256, item.previousSha256].includes(hash(value)), 'Owned chat integration was edited; preserving it');
63
+ }
64
+ for (const item of assets) {
65
+ if (item.kind === 'mcp' || item.kind === 'permission') {
66
+ const settings = json(root, item.path);
67
+ const object = value => value && typeof value === 'object' && !Array.isArray(value);
68
+ if (item.kind === 'mcp') check(settings.mcpServers === undefined || object(settings.mcpServers), 'Invalid MCP host settings');
69
+ else check(settings.permissions === undefined || object(settings.permissions) && (settings.permissions.allow === undefined || Array.isArray(settings.permissions.allow) && settings.permissions.allow.every(p => typeof p === 'string')), 'Invalid host permission settings');
70
+ }
71
+ const value = current(root, item);
72
+ if (value !== null) check(hash(value) === hash(item.value) || previous.items.some(p => p.kind === item.kind && p.path === item.path), 'Existing chat integration conflicts; preserving it');
73
+ if (item.kind === 'toml') {
74
+ const file = inside(root, item.path), content = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
75
+ // Conservative conflict detection also covers quoted and inline TOML forms.
76
+ check(!content.replace(block(content) || '', '').includes('augx_decision'), 'Existing Codex server key conflicts');
77
+ }
78
+ }
79
+ return { previous, assets };
80
+ }
81
+ function install(root, host, runtime, requests) {
82
+ const { previous, assets } = preflight(root, host, runtime);
83
+ const policy = config(root);
84
+ check(Number.isSafeInteger(requests) && requests > 0 && requests <= policy.limits.requests, 'Automatic setup requires --requests within configured limit');
85
+ // Disable before any registration mutation so interrupted activation cannot send data.
86
+ if (policy.automatic) { policy.automatic.enabled = false; atomic(inside(root, '.augx-decision/config.json'), policy); }
87
+ for (const item of assets) {
88
+ const value = current(root, item), owned = previous.items.find(p => p.kind === item.kind && p.path === item.path);
89
+ if (value !== null && !owned) continue;
90
+ const entry = { kind: item.kind, path: item.path, sha256: hash(item.value), ...(value !== null ? { previousSha256: hash(value) } : {}) };
91
+ // Record intent first. An interrupted write stays disabled and is repairable on rerun.
92
+ previous.items = previous.items.filter(p => !(p.kind === item.kind && p.path === item.path));
93
+ previous.items.push(entry); atomic(inside(root, receiptName), previous);
94
+ const file = inside(root, item.path);
95
+ if (item.kind === 'file') writeText(file, item.value);
96
+ else if (item.kind === 'toml') {
97
+ const content = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
98
+ writeText(file, value === null ? content + '\n' + item.value + '\n' : content.replace(value, item.value));
99
+ } else {
100
+ const content = json(root, item.path);
101
+ if (item.kind === 'mcp') { content.mcpServers ||= {}; content.mcpServers.augx_decision = item.value; }
102
+ else { content.permissions ||= {}; content.permissions.allow ||= []; if (!content.permissions.allow.includes(permission)) content.permissions.allow.push(permission); }
103
+ atomic(file, content);
104
+ }
105
+ delete entry.previousSha256; atomic(inside(root, receiptName), previous);
106
+ }
107
+ policy.automatic = { capabilities: ['classify', 'rank-retrieval'], dataClasses: ['public'], timeoutMs: Math.min(10000, policy.limits.requestMs), ...policy.automatic, enabled: true, host, requests };
108
+ policy.allowProviderData = true;
109
+ atomic(inside(root, '.augx-decision/config.json'), policy);
110
+ return status(root);
111
+ }
112
+ function disable(root) {
113
+ const policy = config(root);
114
+ if (policy.automatic) { policy.automatic.enabled = false; atomic(inside(root, '.augx-decision/config.json'), policy); }
115
+ const previous = receipt(root), preserved = [];
116
+ for (const item of previous.items) {
117
+ const value = current(root, item);
118
+ if (value === null) continue;
119
+ if (hash(value) !== item.sha256) { preserved.push(item); continue; }
120
+ const file = inside(root, item.path);
121
+ if (item.kind === 'file') fs.unlinkSync(file);
122
+ else if (item.kind === 'toml') writeText(file, fs.readFileSync(file, 'utf8').replace(value, ''));
123
+ else {
124
+ const content = json(root, item.path);
125
+ if (item.kind === 'mcp') delete content.mcpServers.augx_decision;
126
+ else content.permissions.allow = content.permissions.allow.filter(p => p !== permission);
127
+ atomic(file, content);
128
+ }
129
+ }
130
+ if (preserved.length) atomic(inside(root, receiptName), { ...previous, items: preserved });
131
+ else if (fs.existsSync(inside(root, receiptName))) fs.unlinkSync(inside(root, receiptName));
132
+ return { enabled: false, preserved: preserved.map(p => p.path), retained: 'Automatic request ledger and all unrelated host settings' };
133
+ }
134
+ function status(root) {
135
+ try {
136
+ const policy = config(root), saved = policy.automatic;
137
+ receipt(root);
138
+ const installation = inside(root, '.augx-decision/receipt.json');
139
+ const runtime = fs.existsSync(installation) ? read(installation).runtime : process.execPath;
140
+ const required = saved ? plan(root, saved.host, runtime || process.execPath) : [];
141
+ return { enabled: saved?.enabled === true, host: saved?.host || null,
142
+ registrationIntact: required.length > 0 && required.every(item => { const value = current(root, item); return value !== null && hash(value) === hash(item.value); }),
143
+ providerDataAllowed: policy.allowProviderData, requestLimit: saved?.requests ?? 0,
144
+ requestsUsed: fs.existsSync(inside(root, '.augx-decision/automatic-ledger.json')) ? read(inside(root, '.augx-decision/automatic-ledger.json')).requests : 0,
145
+ hostSession: 'NOT VERIFIED', connectivity: 'NOT VERIFIED',
146
+ next: 'Restart the host in this trusted project; approve its project MCP server once if requested. Managed deny/ask rules remain authoritative.' };
147
+ } catch { return { enabled: false, registrationIntact: false, hostSession: 'NOT VERIFIED', connectivity: 'NOT VERIFIED', error: 'Inspect automatic policy, host settings and chat ownership receipt locally' }; }
148
+ }
149
+ module.exports = { install, disable, status, preflight };
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { automatic, inputSchema, fallback } = require('./automatic.cjs');
6
+
7
+ // Narrow MCP stdio surface: no sampling, subprocess tools, resources or provider endpoint overrides.
8
+ function serve(root, host, input = process.stdin, output = process.stdout) {
9
+ let negotiated = false, initialized = false, pending = Buffer.alloc(0), dropping = false;
10
+ const running = new Map();
11
+ const send = message => output.write(JSON.stringify(message) + '\n');
12
+ const error = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } });
13
+ const toolResult = value => ({ content: [{ type: 'text', text: JSON.stringify(value) }], isError: false });
14
+ async function handle(message) {
15
+ if (!message || message.jsonrpc !== '2.0' || typeof message.method !== 'string') { error(null, -32600, 'Invalid request'); return; }
16
+ const hasId = Object.hasOwnProperty.call(message, 'id');
17
+ const id = message.id;
18
+ if (hasId && !(typeof id === 'string' || Number.isSafeInteger(id))) { error(null, -32600, 'Invalid request identity'); return; }
19
+ if (message.method === 'notifications/cancelled') { running.get(message.params?.requestId)?.abort(); return; }
20
+ if (message.method === 'notifications/initialized' && negotiated) { initialized = true; return; }
21
+ if (!hasId) return;
22
+ if (message.method === 'ping') { send({ jsonrpc: '2.0', id, result: {} }); return; }
23
+ if (message.method === 'initialize' && !negotiated) {
24
+ negotiated = true;
25
+ const supported = ['2024-11-05', '2025-03-26', '2025-06-18', '2025-11-25'];
26
+ send({ jsonrpc: '2.0', id, result: { protocolVersion: supported.includes(message.params?.protocolVersion) ? message.params.protocolVersion : '2025-11-25',
27
+ capabilities: { tools: {} }, serverInfo: { name: 'augx-decision', version: '1.1.0' },
28
+ instructions: 'Use judge selectively for ambiguous ordinary-task classification or retrieval relevance. Saved policy enforces data and request limits. Continue normal work after judgments or fallbacks.' } }); return;
29
+ }
30
+ if (!initialized) { error(id, -32000, 'Initialize the MCP session first'); return; }
31
+ if (message.method === 'tools/list') {
32
+ send({ jsonrpc: '2.0', id, result: { tools: [{ name: 'judge',
33
+ description: 'Classify an ambiguous task among supplied categories or rank retrieved evidence for relevance. Use during ordinary work without a user command when deterministic selection is insufficient. Sends only supplied de-identified public or approved internal context to the configured Jev provider under saved policy. Returns typed advice or an explicit safe fallback. Does not execute actions or grant permissions.',
34
+ inputSchema, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true } }] } }); return;
35
+ }
36
+ if (message.method !== 'tools/call') { error(id, -32601, 'Unsupported method'); return; }
37
+ if (message.params?.name !== 'judge') { error(id, -32602, 'Unknown tool'); return; }
38
+ if (running.size) { send({ jsonrpc: '2.0', id, result: toolResult(fallback('writer-busy')) }); return; }
39
+ const controller = new AbortController(); running.set(id, controller);
40
+ try { send({ jsonrpc: '2.0', id, result: toolResult(await automatic(root, host, message.params.arguments, { signal: controller.signal })) }); }
41
+ catch { send({ jsonrpc: '2.0', id, result: toolResult(fallback('runtime-unavailable')) }); }
42
+ finally { running.delete(id); }
43
+ }
44
+ const data = chunk => {
45
+ // Bound each line before JSON parsing, including newline-free malicious input.
46
+ const bytes = Buffer.from(chunk);
47
+ for (let offset = 0; offset < bytes.length;) {
48
+ const newline = bytes.indexOf(10, offset), finish = newline < 0 ? bytes.length : newline;
49
+ if (!dropping) {
50
+ if (pending.length + finish - offset > 32768) { pending = Buffer.alloc(0); dropping = true; error(null, -32600, 'Request exceeds size bound'); }
51
+ else pending = Buffer.concat([pending, bytes.subarray(offset, finish)]);
52
+ }
53
+ if (newline < 0) break;
54
+ if (!dropping && pending.length) { try { void handle(JSON.parse(pending.toString('utf8'))); } catch { error(null, -32700, 'Invalid JSON'); } }
55
+ pending = Buffer.alloc(0); dropping = false; offset = finish + 1;
56
+ }
57
+ };
58
+ const stop = () => { for (const controller of running.values()) controller.abort(); };
59
+ input.on('data', data); input.on('end', stop); input.on('close', stop);
60
+ return { stop, close: () => { stop(); input.removeListener('data', data); input.removeListener('end', stop); input.removeListener('close', stop); } };
61
+ }
62
+ if (require.main === module) {
63
+ try {
64
+ const root = fs.realpathSync(path.resolve(process.argv[2] || '.')), host = process.argv[3];
65
+ if (Number(process.versions.node.split('.')[0]) < 22 || !['codex', 'claude-code'].includes(host)) throw new Error('Unsupported host/runtime');
66
+ const server = serve(root, host);
67
+ const shutdown = () => { server.stop(); process.stdin.destroy(); };
68
+ process.once('SIGINT', shutdown); process.once('SIGTERM', shutdown);
69
+ } catch { process.stderr.write('Augx decision chat runtime unavailable; inspect setup and doctor.\n'); process.exitCode = 2; }
70
+ }
71
+ module.exports = { serve };
@@ -6,3 +6,16 @@ export interface WorkerRegistration { id: string; description: string; capabilit
6
6
  export interface WorkerContext { task: { id: string; goal: string; kind: string }; sources: { path: string; sha256: string; content: string }[]; worker: string }
7
7
  export interface Task { id: string; goal: string; kind: 'research' | 'write' | 'review'; capabilities: string[]; sources: string[]; acceptance: { minBytes: number; contains: string[] } }
8
8
  export interface Verification { passed: boolean; reason: string; sha256?: string; bytes?: number }
9
+ export interface AutomaticPolicy {
10
+ enabled: boolean;
11
+ host: 'codex' | 'claude-code';
12
+ capabilities: ('classify' | 'rank-retrieval')[];
13
+ dataClasses: ('public' | 'internal')[];
14
+ requests: number;
15
+ timeoutMs: number;
16
+ }
17
+ export type AutomaticResult = { status: 'fallback'; reason: string; next: string } | {
18
+ status: 'judgment'; capability: 'classify' | 'rank-retrieval'; outcome: string;
19
+ selected: string | string[]; answers: Record<string, Answer>; model: string;
20
+ provenance: 'typesafe-sdk-0.7.0'; requestsUsed: number; next: string;
21
+ };
@@ -90,12 +90,21 @@ function unchanged(root, files) {
90
90
  async function setup(root, options = {}) {
91
91
  const environment = detect(root, options.portable), host = options.host || 'codex';
92
92
  check(['codex', 'claude-code'].includes(host), 'Supported skill hosts: codex, claude-code');
93
+ check(!(options.automatic && options.disableAutomatic), 'Choose automatic activation or disabling');
94
+ if (options.automatic) {
95
+ const policyFile = inside(root, '.augx-decision/config.json');
96
+ const policy = fs.existsSync(policyFile) ? config(root) : require('../examples/config.json');
97
+ check(Number.isSafeInteger(Number(options.requests)) && Number(options.requests) > 0 && Number(options.requests) <= policy.limits.requests, 'Automatic setup requires --requests within configured limit');
98
+ require('./chat-install.cjs').preflight(root, host, environment.runtime);
99
+ }
93
100
  const plan = { scope: root, ...environment, selectedHost: host, operations: [environment.version ? 'Reuse compatible Node runtime and npm' : 'Download checksum-pinned portable Node with npm', 'npm ci: pinned isolated SDK, scripts disabled', 'Copy checksum-pinned official TypeSafe skill', 'Preserve or create validated config', 'Verify loading and write redacted ownership receipt'], credentialsRequired: false };
101
+ plan.automatic = options.automatic ? { enabled: true, host, publicProviderDataConsent: true, cumulativeRequests: Number(options.requests), activation: 'Native MCP registration and implicit skill; restart/trust required; host session NOT VERIFIED' } : options.disableAutomatic ? { enabled: false } : { unchanged: true };
94
102
  if (options.dryRun) return { dryRun: true, plan };
95
103
  const unlock = lock(root, '.augx-decision/install.lock');
96
104
  const receiptPath = inside(root, '.augx-decision/receipt.json');
97
105
  const journalPath = inside(root, '.augx-decision/install-journal.json');
98
106
  try {
107
+ if (options.disableAutomatic) return { automatic: require('./chat-install.cjs').disable(root) };
99
108
  const previous = fs.existsSync(receiptPath) ? read(receiptPath) : null;
100
109
  if (previous) unchanged(root, Object.fromEntries(Object.entries(previous.files).filter(([p]) => p !== '.augx-decision/config.json')));
101
110
  const software = inside(root, '.augx-decision/software');
@@ -149,7 +158,8 @@ async function setup(root, options = {}) {
149
158
  if (createdConfig || previous?.files['.augx-decision/config.json'] || journal.files['.augx-decision/config.json']) files['.augx-decision/config.json'] = previous?.files['.augx-decision/config.json'] || journal.files['.augx-decision/config.json'] || hash(fs.readFileSync(configFile));
150
159
  const receipt = { schemaVersion: 1, status: 'installed', sdk: pins.sdkVersion, runtime: environment.runtime, runtimeVersion: execute(environment.runtime, ['--version'], 10000), host, skillCommit: pins.skillCommit, files };
151
160
  atomic(receiptPath, receipt); fs.unlinkSync(journalPath);
152
- return { softwareInstalled: true, configurationValid: true, credentialsAvailable: !!process.env.TYPESAFE_API_KEY, connectivity: 'NOT VERIFIED', liveEnabled: false, receipt: '.augx-decision/receipt.json' };
161
+ const automatic = options.automatic ? require('./chat-install.cjs').install(root, host, environment.runtime, Number(options.requests)) : require('./chat-install.cjs').status(root);
162
+ return { softwareInstalled: true, configurationValid: true, credentialsAvailable: !!process.env.TYPESAFE_API_KEY, connectivity: 'NOT VERIFIED', liveEnabled: false, automatic, receipt: '.augx-decision/receipt.json' };
153
163
  } finally { unlock(); }
154
164
  }
155
165
  function doctor(root) {
@@ -164,13 +174,16 @@ function doctor(root) {
164
174
  execute(environment.runtime, ['-e', 'const s=require(process.argv[1]);if(typeof s.TypeSafeClient!=="function")process.exit(2)', inside(root, '.augx-decision/software/sdk/node_modules/@typesafe-ai/sdk')], 10000);
165
175
  softwareInstalled = true;
166
176
  } catch { /* A partial installation never reports ready. */ }
167
- return { ...environment, softwareInstalled, configurationValid, credentialsAvailable: !!process.env.TYPESAFE_API_KEY, connectivity: 'NOT VERIFIED', liveEnabled: false, next: softwareInstalled ? 'Use --live with an explicit --requests budget and allowProviderData=true for a provider probe' : 'Run augx decision setup; partial installs can be retried' };
177
+ return { ...environment, softwareInstalled, configurationValid, credentialsAvailable: !!process.env.TYPESAFE_API_KEY, connectivity: 'NOT VERIFIED', liveEnabled: false, automatic: require('./chat-install.cjs').status(root), next: softwareInstalled ? 'Inspect automatic readiness, or use --live with an explicit --requests budget for a manual provider probe' : 'Run augx decision setup; partial installs can be retried' };
168
178
  }
169
179
  function remove(root) {
170
180
  const unlock = lock(root, '.augx-decision/install.lock');
171
181
  try {
172
182
  const receiptPath = inside(root, '.augx-decision/receipt.json'), receipt = read(receiptPath), removed = [], preserved = [];
173
183
  check(receipt.files && Object.keys(receipt.files).every(ownedPath), 'Unsupported receipt ownership');
184
+ const configFile = inside(root, '.augx-decision/config.json');
185
+ const hasAutomatic = fs.existsSync(configFile) && !!read(configFile).automatic;
186
+ const chat = hasAutomatic || fs.existsSync(inside(root, '.augx-decision/chat-receipt.json')) ? require('./chat-install.cjs').disable(root) : null;
174
187
  for (const [relative, digest] of Object.entries(receipt.files)) {
175
188
  check(ownedPath(relative), 'Unsupported receipt ownership');
176
189
  const file = inside(root, relative);
@@ -180,7 +193,7 @@ function remove(root) {
180
193
  }
181
194
  if (!preserved.length) fs.unlinkSync(receiptPath);
182
195
  else atomic(receiptPath, { ...receipt, status: 'removed-with-preserved-edits', files: Object.fromEntries(preserved.map(p => [p, receipt.files[p]])) });
183
- return { removed: removed.length, preserved, retained: 'Run data, user files, credentials, unrelated runtimes, and empty directories' };
196
+ return { removed: removed.length, preserved, automatic: chat, retained: 'Run data, automatic request ledger, user files, credentials, unrelated runtimes, and empty directories' };
184
197
  } finally { unlock(); }
185
198
  }
186
199
  module.exports = { setup, doctor, remove, detect, download, inventory, execute, processEnv, portable };