@inneranimalmedia/agentsam-sdk 2.6.5 → 2.6.7

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 (371) hide show
  1. package/AGENTSAM.md +29 -0
  2. package/apps/README.md +5 -0
  3. package/apps/cad-creator/README.md +4 -4
  4. package/apps/cad-creator/shared/cad/package.json +1 -1
  5. package/apps/client-cms-editor/AGENTS.md +12 -7
  6. package/apps/client-cms-editor/README.md +76 -48
  7. package/apps/client-cms-editor/agentsam.app.json +26 -9
  8. package/apps/client-cms-editor/backend/package.json +20 -3
  9. package/apps/client-cms-editor/backend/src/api/client.ts +134 -101
  10. package/apps/client-cms-editor/backend/src/index.ts +1 -1
  11. package/apps/client-cms-editor/backend/src/model.ts +11 -115
  12. package/apps/client-cms-editor/backend/src/preview/bridge.ts +1 -1
  13. package/apps/client-cms-editor/backend/tsconfig.json +6 -1
  14. package/apps/client-cms-editor/bin/agentsam-cms.js +262 -0
  15. package/apps/client-cms-editor/bin/agentsam-cms.mjs +2 -228
  16. package/apps/client-cms-editor/frontend/package.json +16 -7
  17. package/apps/client-cms-editor/frontend/src/AgentSamDrawer.tsx +9 -41
  18. package/apps/client-cms-editor/frontend/src/CmsAgentSurface.tsx +19 -174
  19. package/apps/client-cms-editor/frontend/src/adapters/heuristic.ts +29 -0
  20. package/apps/client-cms-editor/frontend/src/adapters/http.ts +628 -0
  21. package/apps/client-cms-editor/frontend/src/adapters/memory.ts +510 -0
  22. package/apps/client-cms-editor/frontend/src/editor/CmsEditor.tsx +213 -0
  23. package/apps/client-cms-editor/frontend/src/editor/CmsEditorProvider.tsx +20 -0
  24. package/apps/client-cms-editor/frontend/src/editor/canvas/PreviewCanvas.tsx +53 -0
  25. package/apps/client-cms-editor/frontend/src/{CmsEditor.tsx → editor/legacy/CmsEditorPrototype.tsx} +52 -23
  26. package/apps/client-cms-editor/frontend/src/editor/useCmsEditorController.ts +218 -0
  27. package/apps/client-cms-editor/frontend/src/index.ts +19 -5
  28. package/apps/client-cms-editor/frontend/src/lib/agent-host.ts +24 -0
  29. package/apps/client-cms-editor/frontend/src/main.tsx +82 -8
  30. package/apps/client-cms-editor/frontend/src/mount.tsx +92 -30
  31. package/apps/client-cms-editor/frontend/src/styles/agentsam-drawer.css +1 -1
  32. package/apps/client-cms-editor/frontend/src/styles/cmsShell.css +8 -8
  33. package/apps/client-cms-editor/frontend/src/styles/studio.css +55 -3
  34. package/apps/client-cms-editor/frontend/tsconfig.json +12 -1
  35. package/apps/client-cms-editor/frontend/vite.config.ts +12 -0
  36. package/apps/client-cms-editor/package-lock.json +973 -134
  37. package/apps/client-cms-editor/package.json +118 -6
  38. package/apps/client-cms-editor/reference/harvest/HARVEST_RECEIPT.json +201 -0
  39. package/apps/client-cms-editor/reference/harvest/PROVENANCE_HISTORY.txt +10 -0
  40. package/apps/client-cms-editor/reference/harvest/README.md +8 -0
  41. package/apps/client-cms-editor/reference/harvest/plans/ARCHIVE-INTAKE.md +135 -0
  42. package/apps/client-cms-editor/reference/harvest/plans/CHATGPT-IDENTITY-HARVEST.md +83 -0
  43. package/apps/client-cms-editor/reference/harvest/plans/CMS-EDITOR-HARVEST.md +166 -0
  44. package/apps/client-cms-editor/reference/harvest/plans/HARVEST-INDEX.md +196 -0
  45. package/apps/client-cms-editor/reference/harvest/plans/INNERANIMALS-CONTENT-001.md +137 -0
  46. package/apps/client-cms-editor/reference/harvest/plans/NO-IMPLICIT-SIDE-EFFECTS.md +87 -0
  47. package/apps/client-cms-editor/reference/harvest/plans/STOREFRONT-SURFACE-MAP.md +140 -0
  48. package/apps/client-cms-editor/reference/harvest/plans/THEME-INNERANIMALS-HARVEST.md +137 -0
  49. package/apps/client-cms-editor/reference/harvest/plans/TOOLING-LAB.md +63 -0
  50. package/apps/client-cms-editor/reference/harvest/plans/harvest-manifest.json +97 -0
  51. package/apps/client-cms-editor/reference/harvest/plans/local-cms-harvest-schema.sql +328 -0
  52. package/apps/client-cms-editor/shared/cms/package.json +17 -7
  53. package/apps/client-cms-editor/shared/cms/src/adapter.ts +204 -0
  54. package/apps/client-cms-editor/shared/cms/src/agent-context.ts +7 -5
  55. package/apps/client-cms-editor/shared/cms/src/editor-types.ts +32 -0
  56. package/apps/client-cms-editor/shared/cms/src/host.ts +82 -0
  57. package/apps/client-cms-editor/shared/cms/src/index.ts +4 -0
  58. package/apps/client-cms-editor/shared/cms/src/map.ts +115 -0
  59. package/apps/client-cms-editor/shared/cms/src/starter-pack.ts +158 -0
  60. package/contracts/source-types.v1.json +353 -0
  61. package/docs/CMS_CONTEXTUAL_COMPOSER.md +1 -1
  62. package/docs/PRODUCT_LIFECYCLE.md +566 -0
  63. package/docs/THEME_REFINERY.md +2 -2
  64. package/docs/architecture/AGENTSAM_RUNTIME_PROTOCOL.md +40 -20
  65. package/docs/content-studio/REVISION_GATE_2026-09-27.md +1 -1
  66. package/docs/plans/LOCAL_STUDIO_DESKTOP_RELEASE_2026-09-29.md +150 -0
  67. package/migrations/d1/0017_identity_native_oauth.sql +21 -0
  68. package/native/agentsam-machine/Cargo.lock +426 -0
  69. package/native/agentsam-machine/Cargo.toml +9 -0
  70. package/native/agentsam-machine/cli/Cargo.toml +14 -0
  71. package/native/agentsam-machine/cli/src/main.rs +77 -0
  72. package/native/agentsam-machine/core/Cargo.toml +15 -0
  73. package/native/agentsam-machine/core/src/assets.rs +790 -0
  74. package/native/agentsam-machine/core/src/bound.rs +298 -0
  75. package/native/agentsam-machine/core/src/enrich.rs +706 -0
  76. package/native/agentsam-machine/core/src/frontend.rs +442 -0
  77. package/native/agentsam-machine/core/src/lib.rs +1086 -0
  78. package/native/agentsam-machine/core/src/liquid.rs +528 -0
  79. package/native/agentsam-machine/core/src/source_types.rs +78 -0
  80. package/package.json +51 -21
  81. package/packages/agentsam-brand/README.md +1 -1
  82. package/packages/agentsam-brand/package.json +4 -4
  83. package/packages/agentsam-brand/src/index.js +1 -1
  84. package/packages/agentsam-contracts/package.json +13 -3
  85. package/packages/agentsam-contracts/src/tools.ts +22 -0
  86. package/packages/agentsam-errors/package.json +13 -3
  87. package/packages/agentsam-knowledge/package.json +18 -4
  88. package/packages/agentsam-knowledge/src/autorag/index.js +10 -3
  89. package/packages/agentsam-knowledge/src/backends/index.js +33 -1
  90. package/packages/agentsam-knowledge/test/autorag.test.mjs +60 -1
  91. package/packages/agentsam-nav/package.json +24 -6
  92. package/packages/agentsam-queue-control/README.md +1 -1
  93. package/packages/agentsam-queue-control/package.json +7 -2
  94. package/packages/agentsam-rapid-rust/src/main.rs +1 -1
  95. package/packages/agentsam-repository/package.json +13 -3
  96. package/packages/agentsam-repository/src/source-types.js +8 -0
  97. package/packages/agentsam-vault/package.json +14 -4
  98. package/packages/agentsam-workbench/package.json +15 -4
  99. package/packages/agentsam-workbench/src/agent/ToolPermissionRequest.tsx +94 -0
  100. package/packages/agentsam-workbench/src/agent/index.ts +2 -0
  101. package/packages/agentsam-workbench/src/agent/tool-permission.css +134 -0
  102. package/packages/connectors/cloudflare/package.json +13 -3
  103. package/packages/connectors/cloudflare/src/api-client.js +3 -2
  104. package/packages/connectors/cloudflare/src/families/vectorize.js +127 -0
  105. package/packages/connectors/cloudflare/src/index.js +1 -0
  106. package/packages/heuristic-theme/README.md +2 -2
  107. package/packages/heuristic-theme/package.json +8 -3
  108. package/packages/heuristic-theme/src/registry.js +2 -2
  109. package/packages/heuristic-theme/src/theme.js +1 -1
  110. package/packages/heuristic-theme/test/theme.test.mjs +1 -1
  111. package/packages/identity/.agentsam/features/oauth-login-portal/agentsam.feature.json +1 -1
  112. package/packages/identity/.agentsam/features/oauth-login-portal/providers.json +27 -7
  113. package/packages/identity/README.md +2 -2
  114. package/packages/identity/migrations/D1_SCHEMA_MAPPING.md +18 -15
  115. package/packages/identity/migrations/apply-portable.js +109 -0
  116. package/packages/identity/migrations/sqlite/004_identity_oauth_consent_catalog.sql +1 -1
  117. package/packages/identity/migrations/sqlite/005_identity_company_native.sql +52 -0
  118. package/packages/identity/package.json +27 -6
  119. package/packages/identity/schema/agentsam.identity/manifest.json +101 -0
  120. package/packages/identity/scripts/local-identity-bridge.mjs +13 -7
  121. package/packages/identity/scripts/preview-auth-portal.mjs +6 -6
  122. package/packages/identity/src/adapters/cloudflare-d1/index.js +8 -401
  123. package/packages/identity/src/adapters/iam-compat/index.js +540 -0
  124. package/packages/identity/src/adapters/portable-d1/index.js +18 -0
  125. package/packages/identity/src/adapters/portable-store.js +479 -0
  126. package/packages/identity/src/adapters/sqlite/index.js +13 -312
  127. package/packages/identity/src/contracts/auth-config.js +0 -1
  128. package/packages/identity/src/contracts/identity-store.js +56 -5
  129. package/packages/identity/src/contracts/provider.js +1 -0
  130. package/packages/identity/src/contracts/sign-in-options.js +104 -0
  131. package/packages/identity/src/core/constants.js +1 -1
  132. package/packages/identity/src/core/session-policy.js +31 -0
  133. package/packages/identity/src/frontend/auth-portal/pages/login.html +6 -6
  134. package/packages/identity/src/frontend/auth-portal/pages/reset.html +5 -5
  135. package/packages/identity/src/frontend/auth-portal/pages/signup.html +5 -5
  136. package/packages/identity/src/frontend/auth-portal/shared/company-branding.js +1 -1
  137. package/packages/identity/src/frontend/auth-portal/shared/desktop-identity-bridge.js +6 -37
  138. package/packages/identity/src/index.js +28 -1
  139. package/packages/identity/src/migrations/README.md +23 -23
  140. package/packages/identity/src/oauth/README.md +1 -1
  141. package/packages/identity/src/oauth/credentials.js +10 -11
  142. package/packages/identity/src/oauth/google-desktop-exchange.js +195 -27
  143. package/packages/identity/src/oauth/iam-platform.js +21 -9
  144. package/packages/identity/src/oauth/native-handoff.js +136 -0
  145. package/packages/identity/src/providers/chatgpt/headers.js +65 -0
  146. package/packages/identity/src/providers/chatgpt/index.js +86 -0
  147. package/packages/identity/src/providers/chatgpt/mapper.js +43 -0
  148. package/packages/identity/src/providers/chatgpt/paths.js +45 -0
  149. package/packages/identity/src/providers/github/oauth.js +1 -2
  150. package/packages/identity/src/providers/github/profile.js +16 -2
  151. package/packages/identity/src/providers/index.js +11 -3
  152. package/packages/identity/src/server/identity-service.js +2 -1
  153. package/packages/identity/src/server/worker-router.js +71 -18
  154. package/packages/identity/tests/chatgpt-provider.test.mjs +75 -0
  155. package/packages/identity/tests/google-desktop-identity-login.test.mjs +210 -0
  156. package/packages/identity/tests/identity-init-scaffold.test.mjs +15 -4
  157. package/packages/identity/tests/lane1-identity-store-parity.test.mjs +527 -0
  158. package/packages/identity/tests/lane1-packed-consumer.test.mjs +175 -0
  159. package/packages/identity/tests/native-oauth-handoff.test.mjs +292 -0
  160. package/packages/identity/tests/oauth-credentials.test.mjs +4 -4
  161. package/packages/identity/tests/preview-auth-portal.test.mjs +4 -2
  162. package/packages/identity/tests/session-routes-policy.test.mjs +13 -1
  163. package/packages/identity/tests/worker-runtime-boundary.test.mjs +11 -0
  164. package/packages/providers/completeful/package.json +7 -2
  165. package/packages/theme-church-site/package.json +17 -6
  166. package/packages/theme-church-site/src/harvest.json +4 -2
  167. package/packages/theme-church-site/src/index.js +7 -3
  168. package/packages/theme-church-site/test/theme.test.mjs +4 -2
  169. package/packages/theme-companions-site/package.json +17 -6
  170. package/packages/theme-companions-site/src/harvest.json +4 -2
  171. package/packages/theme-companions-site/src/index.js +7 -3
  172. package/packages/theme-companions-site/test/theme.test.mjs +4 -2
  173. package/packages/theme-floors-site/package.json +17 -6
  174. package/packages/theme-floors-site/src/harvest.json +4 -2
  175. package/packages/theme-floors-site/src/index.js +7 -3
  176. package/packages/theme-floors-site/test/theme.test.mjs +4 -2
  177. package/packages/theme-fuelnfree-site/package.json +17 -6
  178. package/packages/theme-fuelnfree-site/src/harvest.json +4 -2
  179. package/packages/theme-fuelnfree-site/src/index.js +7 -3
  180. package/packages/theme-fuelnfree-site/test/theme.test.mjs +4 -2
  181. package/packages/theme-handyman-site/package.json +17 -6
  182. package/packages/theme-handyman-site/src/harvest.json +4 -2
  183. package/packages/theme-handyman-site/src/index.js +7 -3
  184. package/packages/theme-handyman-site/test/theme.test.mjs +4 -2
  185. package/packages/theme-insurance-site/package.json +17 -6
  186. package/packages/theme-insurance-site/src/harvest.json +4 -2
  187. package/packages/theme-insurance-site/src/index.js +7 -3
  188. package/packages/theme-insurance-site/test/theme.test.mjs +4 -2
  189. package/packages/theme-scenes/README.md +1 -1
  190. package/packages/theme-scenes/package.json +4 -3
  191. package/packages/theme-scenes/src/registry.js +187 -0
  192. package/packages/theme-shinshu-site/package.json +17 -6
  193. package/packages/theme-shinshu-site/src/harvest.json +4 -2
  194. package/packages/theme-shinshu-site/src/index.js +7 -3
  195. package/packages/theme-shinshu-site/test/theme.test.mjs +4 -2
  196. package/packages/work-graph/package.json +14 -4
  197. package/protocol/FILEMETA_V1.md +2 -2
  198. package/protocol/capabilities/manifest.json +1 -1
  199. package/protocol/database/agentsam.schema-pack.v1.schema.json +72 -0
  200. package/protocol/presets/catalog.json +2 -2
  201. package/protocol/theme-refinery/lineage-registry.json +105 -0
  202. package/protocol/theme-refinery/product-metadata.schema.json +21 -1
  203. package/skills/grok-auth/SKILL.md +110 -0
  204. package/skills/grok-auth/agentsam.skill.json +25 -0
  205. package/skills/grok-auth/references/grok-identity.md +64 -0
  206. package/skills/grok-auth/references/per-user-data.md +49 -0
  207. package/skills/grok-auth/references/prewired-and-env.md +54 -0
  208. package/skills/grok-auth/references/session-ui.md +133 -0
  209. package/skills/grok-auth/references/sign-in-methods.md +55 -0
  210. package/skills/grok-auth/references/wiring.md +71 -0
  211. package/skills/grok-building-games/SKILL.md +213 -0
  212. package/skills/grok-building-games/agentsam.skill.json +25 -0
  213. package/skills/grok-building-games/references/3d-libs.md +64 -0
  214. package/skills/grok-building-games/references/ai-pathfinding.md +122 -0
  215. package/skills/grok-building-games/references/audio.md +129 -0
  216. package/skills/grok-building-games/references/babylon.md +202 -0
  217. package/skills/grok-building-games/references/collision-physics.md +122 -0
  218. package/skills/grok-building-games/references/ecs-architecture.md +111 -0
  219. package/skills/grok-building-games/references/game-feel-juice.md +110 -0
  220. package/skills/grok-building-games/references/genres/board-card-chess.md +89 -0
  221. package/skills/grok-building-games/references/genres/endless-runner.md +83 -0
  222. package/skills/grok-building-games/references/genres/fps.md +105 -0
  223. package/skills/grok-building-games/references/genres/platformer-2d.md +97 -0
  224. package/skills/grok-building-games/references/genres/puzzle-match3-tetris.md +131 -0
  225. package/skills/grok-building-games/references/genres/racing-kart.md +106 -0
  226. package/skills/grok-building-games/references/genres/topdown-twin-stick.md +97 -0
  227. package/skills/grok-building-games/references/genres/tower-defense.md +84 -0
  228. package/skills/grok-building-games/references/genres/voxel-minecraft.md +89 -0
  229. package/skills/grok-building-games/references/input.md +139 -0
  230. package/skills/grok-building-games/references/phaser.md +277 -0
  231. package/skills/grok-building-games/references/procedural-generation.md +141 -0
  232. package/skills/grok-building-games/references/save-persistence.md +108 -0
  233. package/skills/grok-building-games/references/threejs-foundational.md +148 -0
  234. package/skills/grok-controls/SKILL.md +274 -0
  235. package/skills/grok-controls/agentsam.skill.json +25 -0
  236. package/skills/grok-design-ui/SKILL.md +122 -0
  237. package/skills/grok-design-ui/agentsam.skill.json +25 -0
  238. package/skills/grok-design-ui/references/animations.md +379 -0
  239. package/skills/grok-design-ui/references/performance.md +88 -0
  240. package/skills/grok-design-ui/references/refined-ui.md +384 -0
  241. package/skills/grok-design-ui/references/surfaces.md +247 -0
  242. package/skills/grok-design-ui/references/typography.md +123 -0
  243. package/skills/grok-game-animation-frames/SKILL.md +84 -0
  244. package/skills/grok-game-animation-frames/agentsam.skill.json +25 -0
  245. package/skills/grok-game-asset-core/SKILL.md +69 -0
  246. package/skills/grok-game-asset-core/agentsam.skill.json +25 -0
  247. package/skills/grok-game-character-consistency/SKILL.md +69 -0
  248. package/skills/grok-game-character-consistency/agentsam.skill.json +25 -0
  249. package/skills/grok-game-tilesets/SKILL.md +65 -0
  250. package/skills/grok-game-tilesets/agentsam.skill.json +25 -0
  251. package/skills/grok-game-ui-icons/SKILL.md +56 -0
  252. package/skills/grok-game-ui-icons/agentsam.skill.json +25 -0
  253. package/skills/grok-generate2dmap/LICENSE +21 -0
  254. package/skills/grok-generate2dmap/SKILL.md +120 -0
  255. package/skills/grok-generate2dmap/SOURCE.md +6 -0
  256. package/skills/grok-generate2dmap/agentsam.skill.json +25 -0
  257. package/skills/grok-generate2dmap/references/deliverables.md +101 -0
  258. package/skills/grok-generate2dmap/references/layered-map-contract.md +209 -0
  259. package/skills/grok-generate2dmap/references/map-strategies.md +341 -0
  260. package/skills/grok-generate2dmap/references/object-production-gate.md +24 -0
  261. package/skills/grok-generate2dmap/references/pipeline.md +149 -0
  262. package/skills/grok-generate2dmap/references/prop-pack-contract.md +174 -0
  263. package/skills/grok-generate2dmap/references/side-scroll-stages.md +29 -0
  264. package/skills/grok-generate2dmap/scripts/compose_layered_preview.py +157 -0
  265. package/skills/grok-generate2dmap/scripts/extract_prop_pack.py +369 -0
  266. package/skills/grok-generate2dsprite/LICENSE +21 -0
  267. package/skills/grok-generate2dsprite/SKILL.md +313 -0
  268. package/skills/grok-generate2dsprite/SOURCE.md +6 -0
  269. package/skills/grok-generate2dsprite/agentsam.skill.json +25 -0
  270. package/skills/grok-generate2dsprite/references/modes.md +124 -0
  271. package/skills/grok-generate2dsprite/references/prompt-rules.md +315 -0
  272. package/skills/grok-generate2dsprite/scripts/generate2dsprite.py +1031 -0
  273. package/skills/grok-generate2dsprite/scripts/make_layout_guide.py +109 -0
  274. package/skills/grok-imagine/SKILL.md +201 -0
  275. package/skills/grok-imagine/agentsam.skill.json +25 -0
  276. package/skills/grok-multiplayer-p2p/SKILL.md +111 -0
  277. package/skills/grok-multiplayer-p2p/agentsam.skill.json +25 -0
  278. package/skills/grok-multiplayer-p2p/references/react-binding.md +144 -0
  279. package/skills/grok-multiplayer-p2p/references/signaling-relay.md +269 -0
  280. package/skills/grok-neon/SKILL.md +157 -0
  281. package/skills/grok-neon/agentsam.skill.json +25 -0
  282. package/skills/grok-og/SKILL.md +102 -0
  283. package/skills/grok-og/agentsam.skill.json +25 -0
  284. package/skills/grok-og/references/brand-pass.md +53 -0
  285. package/skills/grok-og/references/custom-card.md +107 -0
  286. package/skills/grok-og/references/favicon-and-icons.md +48 -0
  287. package/skills/grok-og/references/og-type-contract.md +18 -0
  288. package/skills/grok-og/references/placeholder-card.md +21 -0
  289. package/skills/grok-og/references/x-banner.md +41 -0
  290. package/skills/grok-threejs/SKILL.md +67 -0
  291. package/skills/grok-threejs/agentsam.skill.json +25 -0
  292. package/skills/grok-threejs/references/llms-full.txt +2780 -0
  293. package/skills/grok-video2dsprite/LICENSE +21 -0
  294. package/skills/grok-video2dsprite/SKILL.md +236 -0
  295. package/skills/grok-video2dsprite/SOURCE.md +6 -0
  296. package/skills/grok-video2dsprite/agentsam.skill.json +25 -0
  297. package/skills/grok-video2dsprite/references/pipeline.md +90 -0
  298. package/skills/grok-video2dsprite/references/prompt-rules.md +63 -0
  299. package/skills/grok-video2dsprite/scripts/video2dsprite.py +490 -0
  300. package/skills/grok-xai-api/SKILL.md +152 -0
  301. package/skills/grok-xai-api/agentsam.skill.json +25 -0
  302. package/src/cli/command-catalog.js +46 -4
  303. package/src/cli/dispatch.js +1 -0
  304. package/src/cli.js +10 -0
  305. package/src/cloudflare/runtime-status.js +2 -1
  306. package/src/commands/autorag.js +67 -13
  307. package/src/commands/cheat-sheet.js +29 -4
  308. package/src/commands/codebaseindex.js +45 -2
  309. package/src/commands/knowledge.js +59 -2
  310. package/src/commands/machine-binary.js +103 -0
  311. package/src/commands/machine.js +137 -0
  312. package/src/commands/security.js +67 -4
  313. package/src/commands/setup.js +33 -16
  314. package/src/commands/status.js +8 -1
  315. package/src/features/resolve.js +1 -0
  316. package/src/knowledge/engine.js +21 -2
  317. package/src/knowledge/runtime-discovery.js +127 -0
  318. package/src/lib/identity-scaffold.js +53 -13
  319. package/src/lib/setup/recipes.js +1 -1
  320. package/src/models/discovery.js +40 -22
  321. package/src/models/inventory-core.d.ts +105 -0
  322. package/src/models/inventory-core.js +54 -6
  323. package/src/security/logs.js +3 -0
  324. package/src/ui/cli/help.js +41 -0
  325. package/test/apps-scaffold-contract.test.mjs +3 -2
  326. package/test/cli/api-key-env-whoami.test.mjs +2 -2
  327. package/test/cli/catalog-authority.test.mjs +64 -0
  328. package/test/cli/machine-command.test.mjs +34 -0
  329. package/test/fixtures/project-authority/customer-app/.agentsam/app.json +5 -0
  330. package/test/fixtures/project-authority/customer-app/apps/my-product/index.ts +1 -0
  331. package/test/fixtures/project-authority/customer-app/wrangler.toml +17 -0
  332. package/test/integration/autorag-project-authority.integration.test.mjs +51 -0
  333. package/test/integration/autorag-runtime-discovery.test.mjs +107 -0
  334. package/test/integration/cms-app-scaffold.test.mjs +37 -31
  335. package/test/integration/cms-site-tenancy-contract.test.mjs +28 -17
  336. package/test/integration/codebaseindex-ingest.test.mjs +41 -0
  337. package/test/integration/database-hosted-honesty.test.mjs +49 -0
  338. package/test/integration/desktop-keychain-boundary.test.mjs +45 -0
  339. package/test/integration/hosted-work-host-authority.test.mjs +47 -0
  340. package/test/integration/inventory-eligibility.test.mjs +59 -0
  341. package/test/integration/local-provider-bridge.test.mjs +65 -0
  342. package/test/integration/local-studio-settings-production.test.mjs +40 -0
  343. package/test/integration/lockfile-sync.test.mjs +26 -0
  344. package/test/integration/provider-env-cli.test.mjs +13 -3
  345. package/test/integration/runtime-status.integration.test.mjs +16 -1
  346. package/test/integration/theme-package-registry.test.mjs +31 -0
  347. package/test/repository-snapshot-view.test.mjs +2 -2
  348. package/test/security.test.mjs +14 -0
  349. package/test/terminal-machine-identity.test.mjs +2 -2
  350. package/apps/client-cms-editor/backend/src/demo-bootstrap.ts +0 -145
  351. package/packages/agentsam-nav/dist/Nav.d.ts +0 -43
  352. package/packages/agentsam-nav/dist/NavCollapsible.d.ts +0 -10
  353. package/packages/agentsam-nav/dist/NavContent.d.ts +0 -2
  354. package/packages/agentsam-nav/dist/NavFooter.d.ts +0 -2
  355. package/packages/agentsam-nav/dist/NavGroup.d.ts +0 -3
  356. package/packages/agentsam-nav/dist/NavHeader.d.ts +0 -2
  357. package/packages/agentsam-nav/dist/NavMenu.d.ts +0 -22
  358. package/packages/agentsam-nav/dist/NavProvider.d.ts +0 -35
  359. package/packages/agentsam-nav/dist/NavTrigger.d.ts +0 -2
  360. package/packages/agentsam-nav/dist/Surfaces.d.ts +0 -41
  361. package/packages/agentsam-nav/dist/browser.d.ts +0 -11
  362. package/packages/agentsam-nav/dist/browser.global.js +0 -132
  363. package/packages/agentsam-nav/dist/browser.js +0 -613
  364. package/packages/agentsam-nav/dist/contracts.d.ts +0 -76
  365. package/packages/agentsam-nav/dist/index.d.ts +0 -11
  366. package/packages/agentsam-nav/dist/index.js +0 -614
  367. package/packages/agentsam-nav/dist/legacy.css +0 -83
  368. package/packages/agentsam-nav/dist/shell.css +0 -113
  369. package/packages/agentsam-nav/dist/theme.css +0 -113
  370. package/packages/agentsam-nav/dist/utils.d.ts +0 -1
  371. package/packages/agentsam-repository/src/goap.js.bak-20260922011251 +0 -670
@@ -0,0 +1,1086 @@
1
+ //! AgentSam machine perception core — deterministic inspect receipts.
2
+ //! No Cloudflare, browser, Tauri, or network dependency.
3
+
4
+ mod assets;
5
+ mod bound;
6
+ mod enrich;
7
+ mod frontend;
8
+ mod liquid;
9
+ mod source_types;
10
+
11
+ use bound::{externalize_and_bound, BoundLimits};
12
+ use enrich::enrich_receipt;
13
+ use source_types::SourceTypeIndex;
14
+
15
+ use serde::Serialize;
16
+ use serde_json::Value;
17
+ use sha2::{Digest, Sha256};
18
+ use std::collections::BTreeMap;
19
+ use std::fs::{self, File, Metadata};
20
+ use std::io::{self, Read};
21
+ use std::path::{Path, PathBuf};
22
+ use std::time::{SystemTime, UNIX_EPOCH};
23
+
24
+ pub const RECEIPT_SCHEMA: &str = "agentsam.machine.receipt.v1";
25
+ pub const ENGINE_VERSION: &str = env!("CARGO_PKG_VERSION");
26
+ pub const PARSER_VERSION: &str = "machine-parser.v1";
27
+ pub const ARTIFACT_SCHEMA_VERSION: &str = "machine-artifacts.v1";
28
+
29
+ /// Directories skipped during normal inspect (summarized, not flooded into facts).
30
+ const IGNORE_DIRS: &[&str] = &[
31
+ ".git",
32
+ ".agentsam",
33
+ "node_modules",
34
+ "target",
35
+ "build",
36
+ "dist",
37
+ ".next",
38
+ ".wrangler",
39
+ ".vinext",
40
+ "__pycache__",
41
+ ".cache",
42
+ ".sites-runtime",
43
+ "npm-cache",
44
+ "_cacache",
45
+ ".npm",
46
+ ".pnpm-store",
47
+ ".turbo",
48
+ ".vite",
49
+ ".parcel-cache",
50
+ "coverage",
51
+ ".venv",
52
+ "venv",
53
+ ".vercel",
54
+ ".TemporaryItems",
55
+ ".Trashes",
56
+ ".Spotlight-V100",
57
+ ".fseventsd",
58
+ ];
59
+
60
+ /// Pure Rust domain logic: no Cloudflare, browser, Tauri, or network dependency.
61
+ pub fn normalize_resource_key(input: &str) -> String {
62
+ input
63
+ .trim()
64
+ .to_ascii_lowercase()
65
+ .chars()
66
+ .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '-' })
67
+ .collect::<String>()
68
+ .split('-')
69
+ .filter(|part| !part.is_empty())
70
+ .collect::<Vec<_>>()
71
+ .join("-")
72
+ }
73
+
74
+ #[derive(Debug, Clone, Default)]
75
+ pub struct InspectOptions {
76
+ pub run_id: Option<String>,
77
+ /// When true, walk generated/cache trees instead of summarizing them.
78
+ pub include_generated: bool,
79
+ /// When false, skip writing artifacts / bounding (tests only).
80
+ pub externalize: bool,
81
+ }
82
+
83
+ impl InspectOptions {
84
+ pub fn new() -> Self {
85
+ Self {
86
+ run_id: None,
87
+ include_generated: false,
88
+ externalize: true,
89
+ }
90
+ }
91
+ }
92
+
93
+ #[derive(Debug, Clone, Serialize)]
94
+ pub struct MachineReceipt {
95
+ pub schema: String,
96
+ pub capability: String,
97
+ pub root: String,
98
+ pub run_id: String,
99
+ pub inputs: BTreeMap<String, String>,
100
+ #[serde(skip_serializing_if = "Option::is_none")]
101
+ pub summary: Option<Value>,
102
+ #[serde(skip_serializing_if = "Option::is_none")]
103
+ pub detail: Option<Value>,
104
+ pub facts: Vec<FileFact>,
105
+ pub edges: Vec<Value>,
106
+ pub findings: Vec<Value>,
107
+ pub artifacts: Vec<Value>,
108
+ pub errors: Vec<MachineError>,
109
+ pub stats: InspectStats,
110
+ pub provenance: Provenance,
111
+ }
112
+
113
+ #[derive(Debug, Clone, Serialize)]
114
+ pub struct FileFact {
115
+ pub id: String,
116
+ /// Filesystem object kind: file | symlink
117
+ pub fs_kind: String,
118
+ pub path: String,
119
+ pub size: u64,
120
+ pub mtime_unix_ms: Option<u64>,
121
+ pub sha256: String,
122
+ pub extension: Option<String>,
123
+ pub source: SourceInfo,
124
+ pub content: ContentEvidence,
125
+ pub classification: Classification,
126
+ /// Execution provenance for this fact (not file-content classification).
127
+ pub analysis: FileAnalysis,
128
+ }
129
+
130
+ #[derive(Debug, Clone, Serialize)]
131
+ pub struct FileAnalysis {
132
+ /// True when Machine reused a prior analysis cache entry for this SHA.
133
+ pub cache_hit: bool,
134
+ }
135
+
136
+ #[derive(Debug, Clone, Serialize)]
137
+ pub struct SourceInfo {
138
+ #[serde(rename = "type")]
139
+ pub type_id: String,
140
+ pub language: Option<String>,
141
+ pub syntax: Option<String>,
142
+ /// code | document | asset | binary
143
+ pub kind: Option<String>,
144
+ pub ast_capable: bool,
145
+ }
146
+
147
+ #[derive(Debug, Clone, Serialize)]
148
+ pub struct ContentEvidence {
149
+ /// text | image | archive | binary | database | symlink
150
+ pub kind: String,
151
+ /// Character encoding when content is text (e.g. utf-8). Not a magic signature.
152
+ pub encoding: Option<String>,
153
+ /// Binary magic signature when known (png, zip, wasm, …).
154
+ pub signature: Option<String>,
155
+ }
156
+
157
+ #[derive(Debug, Clone, Serialize)]
158
+ pub struct Classification {
159
+ pub category: String,
160
+ pub role: String,
161
+ pub generated: bool,
162
+ pub include_by_default: bool,
163
+ }
164
+
165
+ #[derive(Debug, Clone, Serialize)]
166
+ pub struct MachineError {
167
+ pub path: String,
168
+ pub operation: String,
169
+ pub message: String,
170
+ }
171
+
172
+ #[derive(Debug, Clone, Default, Serialize)]
173
+ pub struct InspectStats {
174
+ pub files: u64,
175
+ pub symlinks: u64,
176
+ pub directories: u64,
177
+ pub ignored_directories: u64,
178
+ pub skipped_noise_files: u64,
179
+ pub bytes: u64,
180
+ pub excluded_subtrees: Vec<ExcludedSubtree>,
181
+ }
182
+
183
+ #[derive(Debug, Clone, Serialize)]
184
+ pub struct ExcludedSubtree {
185
+ pub path: String,
186
+ pub reason: String,
187
+ pub files: u64,
188
+ pub bytes: u64,
189
+ pub default_disposition: String,
190
+ }
191
+
192
+ #[derive(Debug, Clone, Serialize)]
193
+ pub struct Provenance {
194
+ pub engine: String,
195
+ pub engine_version: String,
196
+ pub parser_version: String,
197
+ pub artifact_schema_version: String,
198
+ pub source_mutated: bool,
199
+ pub network_used: bool,
200
+ pub cache: CacheProvenance,
201
+ }
202
+
203
+ #[derive(Debug, Clone, Serialize)]
204
+ pub struct CacheProvenance {
205
+ pub schema: String,
206
+ pub hits: u64,
207
+ pub misses: u64,
208
+ pub enabled: bool,
209
+ }
210
+
211
+ pub fn inspect_path(target: &Path, requested_run_id: Option<&str>) -> io::Result<MachineReceipt> {
212
+ let mut opts = InspectOptions::new();
213
+ opts.run_id = requested_run_id.map(str::to_owned);
214
+ inspect_path_with_options(target, opts)
215
+ }
216
+
217
+ pub fn inspect_path_with_options(
218
+ target: &Path,
219
+ options: InspectOptions,
220
+ ) -> io::Result<MachineReceipt> {
221
+ let inspection_target = fs::canonicalize(target)?;
222
+ let metadata = fs::symlink_metadata(&inspection_target)?;
223
+
224
+ // Single-file inspect: perception walks the file, but cache/artifacts live under
225
+ // the containing directory (never `<file>/.agentsam/...`).
226
+ let content_root: PathBuf = if metadata.is_file() {
227
+ let parent = inspection_target
228
+ .parent()
229
+ .filter(|p| !p.as_os_str().is_empty())
230
+ .ok_or_else(|| {
231
+ io::Error::new(
232
+ io::ErrorKind::InvalidInput,
233
+ "cannot determine parent directory for file inspect target",
234
+ )
235
+ })?;
236
+ fs::canonicalize(parent)?
237
+ } else {
238
+ inspection_target.clone()
239
+ };
240
+
241
+ let root_text = inspection_target.to_string_lossy().into_owned();
242
+ let content_root_text = content_root.to_string_lossy().into_owned();
243
+ let run_id = options
244
+ .run_id
245
+ .as_deref()
246
+ .filter(|value| !value.trim().is_empty())
247
+ .map(ToOwned::to_owned)
248
+ .unwrap_or_else(|| default_run_id(&root_text));
249
+
250
+ let mut inputs = BTreeMap::new();
251
+ inputs.insert("target".to_string(), root_text.clone());
252
+ inputs.insert("content_root".to_string(), content_root_text.clone());
253
+ inputs.insert(
254
+ "include_generated".to_string(),
255
+ options.include_generated.to_string(),
256
+ );
257
+
258
+ let mut receipt = MachineReceipt {
259
+ schema: RECEIPT_SCHEMA.to_string(),
260
+ capability: "machine.inspect".to_string(),
261
+ root: root_text,
262
+ run_id,
263
+ inputs,
264
+ summary: None,
265
+ detail: None,
266
+ facts: Vec::new(),
267
+ edges: Vec::new(),
268
+ findings: Vec::new(),
269
+ artifacts: Vec::new(),
270
+ errors: Vec::new(),
271
+ stats: InspectStats::default(),
272
+ provenance: Provenance {
273
+ engine: "agentsam-machine".to_string(),
274
+ engine_version: ENGINE_VERSION.to_string(),
275
+ parser_version: PARSER_VERSION.to_string(),
276
+ artifact_schema_version: ARTIFACT_SCHEMA_VERSION.to_string(),
277
+ source_mutated: false,
278
+ network_used: false,
279
+ cache: CacheProvenance {
280
+ schema: "agentsam.machine.cache.v1".to_string(),
281
+ hits: 0,
282
+ misses: 0,
283
+ enabled: true,
284
+ },
285
+ },
286
+ };
287
+
288
+ if metadata.is_file() {
289
+ inspect_file(&content_root, &inspection_target, &metadata, &mut receipt);
290
+ } else if metadata.is_dir() {
291
+ walk_directory(
292
+ &content_root,
293
+ &content_root,
294
+ &mut receipt,
295
+ options.include_generated,
296
+ )?;
297
+ }
298
+
299
+ receipt.facts.sort_by(|a, b| a.path.cmp(&b.path));
300
+ receipt.errors.sort_by(|a, b| {
301
+ a.path
302
+ .cmp(&b.path)
303
+ .then_with(|| a.operation.cmp(&b.operation))
304
+ .then_with(|| a.message.cmp(&b.message))
305
+ });
306
+
307
+ // Incrementality hook: reuse prior fact cache entries when sha256 + parser match.
308
+ apply_fact_cache(&content_root, &mut receipt);
309
+
310
+ enrich_receipt(&content_root, &mut receipt);
311
+ persist_fact_cache(&content_root, &receipt);
312
+
313
+ if options.externalize {
314
+ externalize_and_bound(&content_root, &mut receipt, BoundLimits::default())?;
315
+ }
316
+
317
+ Ok(receipt)
318
+ }
319
+
320
+ fn walk_directory(
321
+ root: &Path,
322
+ current: &Path,
323
+ receipt: &mut MachineReceipt,
324
+ include_generated: bool,
325
+ ) -> io::Result<()> {
326
+ receipt.stats.directories += 1;
327
+ let mut entries = match fs::read_dir(current) {
328
+ Ok(entries) => entries.filter_map(Result::ok).collect::<Vec<_>>(),
329
+ Err(error) => {
330
+ receipt.errors.push(MachineError {
331
+ path: relative_path(root, current),
332
+ operation: "read_dir".to_string(),
333
+ message: error.to_string(),
334
+ });
335
+ return Ok(());
336
+ }
337
+ };
338
+ entries.sort_by_key(|entry| entry.file_name());
339
+
340
+ for entry in entries {
341
+ let path = entry.path();
342
+ let file_name = entry.file_name().to_string_lossy().into_owned();
343
+ let metadata = match fs::symlink_metadata(&path) {
344
+ Ok(metadata) => metadata,
345
+ Err(error) => {
346
+ receipt.errors.push(MachineError {
347
+ path: relative_path(root, &path),
348
+ operation: "metadata".to_string(),
349
+ message: error.to_string(),
350
+ });
351
+ continue;
352
+ }
353
+ };
354
+
355
+ if metadata.file_type().is_symlink() {
356
+ inspect_symlink(root, &path, &metadata, receipt);
357
+ continue;
358
+ }
359
+
360
+ if metadata.is_dir() {
361
+ if !include_generated && is_ignored_directory(&file_name) {
362
+ receipt.stats.ignored_directories += 1;
363
+ let (files, bytes) = summarize_tree(&path);
364
+ receipt.stats.excluded_subtrees.push(ExcludedSubtree {
365
+ path: relative_path(root, &path),
366
+ reason: format!("ignored_directory:{file_name}"),
367
+ files,
368
+ bytes,
369
+ default_disposition: "exclude".to_string(),
370
+ });
371
+ continue;
372
+ }
373
+ // Never recurse into our own machine artifact store even with --include-generated,
374
+ // unless the user pointed inspect directly at it (handled by root walk start).
375
+ if file_name == ".agentsam" && current == root && include_generated {
376
+ // allow if explicitly including generated — still skip machine runs flood
377
+ let machine_runs = path.join("machine").join("runs");
378
+ if machine_runs.exists() {
379
+ receipt.stats.ignored_directories += 1;
380
+ let (files, bytes) = summarize_tree(&machine_runs);
381
+ receipt.stats.excluded_subtrees.push(ExcludedSubtree {
382
+ path: relative_path(root, &machine_runs),
383
+ reason: "ignored_directory:machine_runs".to_string(),
384
+ files,
385
+ bytes,
386
+ default_disposition: "exclude".to_string(),
387
+ });
388
+ }
389
+ }
390
+ walk_directory(root, &path, receipt, include_generated)?;
391
+ continue;
392
+ }
393
+
394
+ if metadata.is_file() {
395
+ if is_noise_file(&file_name) {
396
+ receipt.stats.skipped_noise_files += 1;
397
+ continue;
398
+ }
399
+ inspect_file(root, &path, &metadata, receipt);
400
+ }
401
+ }
402
+
403
+ Ok(())
404
+ }
405
+
406
+ fn summarize_tree(path: &Path) -> (u64, u64) {
407
+ let mut files = 0u64;
408
+ let mut bytes = 0u64;
409
+ let mut stack = vec![path.to_path_buf()];
410
+ while let Some(current) = stack.pop() {
411
+ let Ok(entries) = fs::read_dir(&current) else {
412
+ continue;
413
+ };
414
+ for entry in entries.flatten() {
415
+ let p = entry.path();
416
+ let name = entry.file_name().to_string_lossy().into_owned();
417
+ if is_noise_file(&name) {
418
+ continue;
419
+ }
420
+ let Ok(meta) = fs::symlink_metadata(&p) else {
421
+ continue;
422
+ };
423
+ if meta.is_dir() {
424
+ if is_ignored_directory(&name) {
425
+ continue;
426
+ }
427
+ stack.push(p);
428
+ } else if meta.is_file() {
429
+ files += 1;
430
+ bytes = bytes.saturating_add(meta.len());
431
+ }
432
+ }
433
+ }
434
+ (files, bytes)
435
+ }
436
+
437
+ fn inspect_file(root: &Path, path: &Path, metadata: &Metadata, receipt: &mut MachineReceipt) {
438
+ match hash_file(path) {
439
+ Ok((sha256, prefix)) => {
440
+ let rel = relative_path(root, path);
441
+ let content = classify_content_prefix(&prefix);
442
+ let (source, classification) = classify_semantic(&rel, &content);
443
+ receipt.stats.files += 1;
444
+ receipt.stats.bytes = receipt.stats.bytes.saturating_add(metadata.len());
445
+ receipt.facts.push(FileFact {
446
+ id: format!("file:{rel}"),
447
+ fs_kind: "file".to_string(),
448
+ path: rel.clone(),
449
+ size: metadata.len(),
450
+ mtime_unix_ms: modified_ms(metadata),
451
+ sha256,
452
+ extension: path
453
+ .extension()
454
+ .and_then(|value| value.to_str())
455
+ .map(|value| value.to_ascii_lowercase()),
456
+ source,
457
+ content,
458
+ classification,
459
+ analysis: FileAnalysis { cache_hit: false },
460
+ });
461
+ }
462
+ Err(error) => receipt.errors.push(MachineError {
463
+ path: relative_path(root, path),
464
+ operation: "hash".to_string(),
465
+ message: error.to_string(),
466
+ }),
467
+ }
468
+ }
469
+
470
+ fn inspect_symlink(root: &Path, path: &Path, metadata: &Metadata, receipt: &mut MachineReceipt) {
471
+ match fs::read_link(path) {
472
+ Ok(target) => {
473
+ let literal = target.to_string_lossy().into_owned();
474
+ let digest = sha256_bytes(literal.as_bytes());
475
+ let rel = relative_path(root, path);
476
+ receipt.stats.symlinks += 1;
477
+ receipt.facts.push(FileFact {
478
+ id: format!("symlink:{rel}"),
479
+ fs_kind: "symlink".to_string(),
480
+ path: rel,
481
+ size: literal.len() as u64,
482
+ mtime_unix_ms: modified_ms(metadata),
483
+ sha256: digest,
484
+ extension: path
485
+ .extension()
486
+ .and_then(|value| value.to_str())
487
+ .map(|value| value.to_ascii_lowercase()),
488
+ source: SourceInfo {
489
+ type_id: "unknown".to_string(),
490
+ language: None,
491
+ syntax: None,
492
+ kind: Some("binary".to_string()),
493
+ ast_capable: false,
494
+ },
495
+ content: ContentEvidence {
496
+ kind: "symlink".to_string(),
497
+ encoding: None,
498
+ signature: None,
499
+ },
500
+ classification: Classification {
501
+ category: "link".to_string(),
502
+ role: "symlink".to_string(),
503
+ generated: false,
504
+ include_by_default: false,
505
+ },
506
+ analysis: FileAnalysis { cache_hit: false },
507
+ });
508
+ }
509
+ Err(error) => receipt.errors.push(MachineError {
510
+ path: relative_path(root, path),
511
+ operation: "read_link".to_string(),
512
+ message: error.to_string(),
513
+ }),
514
+ }
515
+ }
516
+
517
+ fn classify_semantic(rel: &str, content: &ContentEvidence) -> (SourceInfo, Classification) {
518
+ let index = SourceTypeIndex::global();
519
+ if let Some(def) = index.for_path(rel) {
520
+ let syntax = index.syntax_for(rel, def);
521
+ let role = match def.kind.as_str() {
522
+ "code" if rel.contains("frontend/") || rel.contains("/src/") => "frontend_source",
523
+ "code" => "source",
524
+ "document" if def.id == "html" => "page_candidate",
525
+ "document" if def.id == "liquid" && rel.starts_with("sections/") => "section_candidate",
526
+ "document" if def.id == "liquid" && rel.starts_with("snippets/") => "snippet_candidate",
527
+ "document" if def.id == "liquid" && rel.starts_with("layout/") => "layout_shell",
528
+ "document" if def.id == "liquid" && rel.starts_with("templates/") => "template_candidate",
529
+ "document" if def.id == "json" && rel.ends_with("theme.json") => "theme_manifest",
530
+ "document" if def.id == "json" && rel.starts_with("templates/") => "template_candidate",
531
+ "document" if def.id == "css" => "stylesheet",
532
+ "asset" if def.id == "svg" => "image",
533
+ "asset" => "asset",
534
+ "binary" => "binary",
535
+ _ => "file",
536
+ };
537
+ let category = match def.kind.as_str() {
538
+ "code" => "source",
539
+ "document" if def.id == "markdown" => "docs",
540
+ "document" => "source",
541
+ "asset" => "asset",
542
+ "binary" => "binary",
543
+ _ => "other",
544
+ };
545
+ return (
546
+ SourceInfo {
547
+ type_id: def.id.clone(),
548
+ language: Some(def.label.clone()),
549
+ syntax,
550
+ kind: Some(def.kind.clone()),
551
+ ast_capable: def.ast,
552
+ },
553
+ Classification {
554
+ category: category.to_string(),
555
+ role: role.to_string(),
556
+ generated: false,
557
+ include_by_default: true,
558
+ },
559
+ );
560
+ }
561
+
562
+ // Unknown is first-class — never emit null type.
563
+ let (kind, category, role) = match content.kind.as_str() {
564
+ "image" => ("asset", "asset", "image"),
565
+ "archive" => ("binary", "archive", "archive"),
566
+ "database" => ("binary", "data", "database"),
567
+ "text" => ("document", "source", "text"),
568
+ _ => ("binary", "binary", "binary"),
569
+ };
570
+ (
571
+ SourceInfo {
572
+ type_id: "unknown".to_string(),
573
+ language: None,
574
+ syntax: None,
575
+ kind: Some(kind.to_string()),
576
+ ast_capable: false,
577
+ },
578
+ Classification {
579
+ category: category.to_string(),
580
+ role: role.to_string(),
581
+ generated: false,
582
+ include_by_default: kind != "binary",
583
+ },
584
+ )
585
+ }
586
+
587
+ fn hash_file(path: &Path) -> io::Result<(String, Vec<u8>)> {
588
+ let mut file = File::open(path)?;
589
+ let mut hasher = Sha256::new();
590
+ let mut prefix = Vec::with_capacity(64);
591
+ let mut buffer = [0u8; 64 * 1024];
592
+
593
+ loop {
594
+ let read = file.read(&mut buffer)?;
595
+ if read == 0 {
596
+ break;
597
+ }
598
+ if prefix.len() < 64 {
599
+ let remaining = 64 - prefix.len();
600
+ prefix.extend_from_slice(&buffer[..read.min(remaining)]);
601
+ }
602
+ hasher.update(&buffer[..read]);
603
+ }
604
+
605
+ Ok((format!("{:x}", hasher.finalize()), prefix))
606
+ }
607
+
608
+ fn sha256_bytes(bytes: &[u8]) -> String {
609
+ let mut hasher = Sha256::new();
610
+ hasher.update(bytes);
611
+ format!("{:x}", hasher.finalize())
612
+ }
613
+
614
+ fn classify_content_prefix(prefix: &[u8]) -> ContentEvidence {
615
+ if prefix.starts_with(b"\x89PNG\r\n\x1a\n") {
616
+ return ContentEvidence {
617
+ kind: "image".into(),
618
+ encoding: None,
619
+ signature: Some("png".into()),
620
+ };
621
+ }
622
+ if prefix.starts_with(&[0xff, 0xd8, 0xff]) {
623
+ return ContentEvidence {
624
+ kind: "image".into(),
625
+ encoding: None,
626
+ signature: Some("jpeg".into()),
627
+ };
628
+ }
629
+ if prefix.starts_with(b"GIF87a") || prefix.starts_with(b"GIF89a") {
630
+ return ContentEvidence {
631
+ kind: "image".into(),
632
+ encoding: None,
633
+ signature: Some("gif".into()),
634
+ };
635
+ }
636
+ if prefix.starts_with(b"%PDF-") {
637
+ return ContentEvidence {
638
+ kind: "document".into(),
639
+ encoding: None,
640
+ signature: Some("pdf".into()),
641
+ };
642
+ }
643
+ if prefix.starts_with(b"PK\x03\x04") {
644
+ return ContentEvidence {
645
+ kind: "archive".into(),
646
+ encoding: None,
647
+ signature: Some("zip".into()),
648
+ };
649
+ }
650
+ if prefix.starts_with(&[0x1f, 0x8b]) {
651
+ return ContentEvidence {
652
+ kind: "archive".into(),
653
+ encoding: None,
654
+ signature: Some("gzip".into()),
655
+ };
656
+ }
657
+ if prefix.starts_with(b"\0asm") {
658
+ return ContentEvidence {
659
+ kind: "binary".into(),
660
+ encoding: None,
661
+ signature: Some("wasm".into()),
662
+ };
663
+ }
664
+ if prefix.starts_with(b"SQLite format 3\0") {
665
+ return ContentEvidence {
666
+ kind: "database".into(),
667
+ encoding: None,
668
+ signature: Some("sqlite".into()),
669
+ };
670
+ }
671
+ if prefix.starts_with(&[0x7f, b'E', b'L', b'F']) {
672
+ return ContentEvidence {
673
+ kind: "binary".into(),
674
+ encoding: None,
675
+ signature: Some("elf".into()),
676
+ };
677
+ }
678
+ if !prefix.contains(&0) && std::str::from_utf8(prefix).is_ok() {
679
+ return ContentEvidence {
680
+ kind: "text".into(),
681
+ encoding: Some("utf-8".into()),
682
+ signature: None,
683
+ };
684
+ }
685
+ ContentEvidence {
686
+ kind: "binary".into(),
687
+ encoding: None,
688
+ signature: None,
689
+ }
690
+ }
691
+
692
+ fn is_ignored_directory(name: &str) -> bool {
693
+ IGNORE_DIRS.iter().any(|candidate| *candidate == name)
694
+ }
695
+
696
+ fn is_noise_file(name: &str) -> bool {
697
+ name == ".DS_Store"
698
+ || name == "Thumbs.db"
699
+ || name == "desktop.ini"
700
+ || name.starts_with("._")
701
+ }
702
+
703
+ fn relative_path(root: &Path, path: &Path) -> String {
704
+ path.strip_prefix(root)
705
+ .unwrap_or(path)
706
+ .to_string_lossy()
707
+ .replace('\\', "/")
708
+ }
709
+
710
+ fn modified_ms(metadata: &Metadata) -> Option<u64> {
711
+ metadata
712
+ .modified()
713
+ .ok()
714
+ .and_then(|value| value.duration_since(UNIX_EPOCH).ok())
715
+ .map(|duration| duration.as_millis().min(u64::MAX as u128) as u64)
716
+ }
717
+
718
+ fn default_run_id(root: &str) -> String {
719
+ let now = SystemTime::now()
720
+ .duration_since(UNIX_EPOCH)
721
+ .map(|duration| duration.as_nanos())
722
+ .unwrap_or_default();
723
+ let seed = format!("{root}:{now}:{}", std::process::id());
724
+ format!("run_{}", &sha256_bytes(seed.as_bytes())[..16])
725
+ }
726
+
727
+ fn cache_dir(root: &Path) -> std::path::PathBuf {
728
+ root.join(".agentsam")
729
+ .join("machine")
730
+ .join("cache")
731
+ .join(PARSER_VERSION)
732
+ }
733
+
734
+ fn apply_fact_cache(root: &Path, receipt: &mut MachineReceipt) {
735
+ let dir = cache_dir(root);
736
+ if !dir.exists() {
737
+ receipt.provenance.cache.misses = receipt.facts.len() as u64;
738
+ return;
739
+ }
740
+ for fact in &mut receipt.facts {
741
+ let path = dir.join(format!("{}.json", fact.sha256));
742
+ if let Ok(text) = fs::read_to_string(&path) {
743
+ if let Ok(cached) = serde_json::from_str::<CachedFact>(&text) {
744
+ if cached.parser_version == PARSER_VERSION
745
+ && cached.engine_version == ENGINE_VERSION
746
+ && cached.source_type == fact.source.type_id
747
+ {
748
+ fact.analysis.cache_hit = true;
749
+ receipt.provenance.cache.hits += 1;
750
+ continue;
751
+ }
752
+ }
753
+ }
754
+ receipt.provenance.cache.misses += 1;
755
+ }
756
+ }
757
+
758
+ fn persist_fact_cache(root: &Path, receipt: &MachineReceipt) {
759
+ let dir = cache_dir(root);
760
+ let _ = fs::create_dir_all(&dir);
761
+ for fact in &receipt.facts {
762
+ let cached = CachedFact {
763
+ parser_version: PARSER_VERSION.to_string(),
764
+ engine_version: ENGINE_VERSION.to_string(),
765
+ sha256: fact.sha256.clone(),
766
+ path: fact.path.clone(),
767
+ source_type: fact.source.type_id.clone(),
768
+ role: fact.classification.role.clone(),
769
+ };
770
+ if let Ok(text) = serde_json::to_string(&cached) {
771
+ let _ = fs::write(dir.join(format!("{}.json", fact.sha256)), text);
772
+ }
773
+ }
774
+ }
775
+
776
+ #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
777
+ struct CachedFact {
778
+ parser_version: String,
779
+ engine_version: String,
780
+ sha256: String,
781
+ path: String,
782
+ source_type: String,
783
+ role: String,
784
+ }
785
+
786
+ #[cfg(test)]
787
+ mod tests {
788
+ use super::*;
789
+ use std::io::Write;
790
+
791
+ #[test]
792
+ fn normalizes_keys_deterministically() {
793
+ assert_eq!(normalize_resource_key(" Hello / World "), "hello-world");
794
+ }
795
+
796
+ #[test]
797
+ fn inspect_classifies_source_types_and_splits_encoding_from_signature() {
798
+ let temp = tempfile::tempdir().unwrap();
799
+ fs::create_dir_all(temp.path().join("src")).unwrap();
800
+ fs::create_dir_all(temp.path().join("target")).unwrap();
801
+ fs::write(
802
+ temp.path().join("src/lib.rs"),
803
+ b"pub fn answer() -> u32 { 42 }\n",
804
+ )
805
+ .unwrap();
806
+ fs::write(temp.path().join("README.md"), b"# Example\n").unwrap();
807
+ fs::write(temp.path().join("target/generated.rs"), b"generated").unwrap();
808
+ fs::write(temp.path().join("._noise"), b"appledouble").unwrap();
809
+
810
+ let mut opts = InspectOptions::new();
811
+ opts.run_id = Some("run_test".into());
812
+ opts.externalize = false;
813
+ let receipt = inspect_path_with_options(temp.path(), opts).unwrap();
814
+ let paths: Vec<_> = receipt.facts.iter().map(|f| f.path.as_str()).collect();
815
+ assert_eq!(paths, vec!["README.md", "src/lib.rs"]);
816
+ assert!(receipt.stats.skipped_noise_files >= 1);
817
+
818
+ let rust = receipt.facts.iter().find(|f| f.path == "src/lib.rs").unwrap();
819
+ assert_eq!(rust.fs_kind, "file");
820
+ assert_eq!(rust.source.type_id, "rust");
821
+ assert_eq!(rust.source.language.as_deref(), Some("Rust"));
822
+ assert_eq!(rust.source.kind.as_deref(), Some("code"));
823
+ assert_eq!(rust.content.encoding.as_deref(), Some("utf-8"));
824
+ assert!(rust.content.signature.is_none());
825
+ assert!(!receipt.findings.is_empty());
826
+ assert!(!receipt.artifacts.is_empty());
827
+ assert_eq!(receipt.stats.excluded_subtrees.len(), 1);
828
+ assert_eq!(receipt.stats.excluded_subtrees[0].path, "target");
829
+ }
830
+
831
+ #[test]
832
+ fn unknown_type_never_null() {
833
+ let temp = tempfile::tempdir().unwrap();
834
+ fs::write(temp.path().join("mystery"), b"not a known type\n").unwrap();
835
+ let mut opts = InspectOptions::new();
836
+ opts.run_id = Some("run_unknown".into());
837
+ opts.externalize = false;
838
+ let receipt = inspect_path_with_options(temp.path(), opts).unwrap();
839
+ let fact = receipt.facts.first().unwrap();
840
+ assert_eq!(fact.source.type_id, "unknown");
841
+ }
842
+
843
+ #[test]
844
+ fn include_generated_walks_ignored_dirs() {
845
+ let temp = tempfile::tempdir().unwrap();
846
+ fs::create_dir_all(temp.path().join("dist")).unwrap();
847
+ fs::write(temp.path().join("dist/out.js"), b"console.log(1)\n").unwrap();
848
+ let mut opts = InspectOptions::new();
849
+ opts.run_id = Some("run_inc".into());
850
+ opts.include_generated = true;
851
+ opts.externalize = false;
852
+ let receipt = inspect_path_with_options(temp.path(), opts).unwrap();
853
+ assert!(receipt.facts.iter().any(|f| f.path == "dist/out.js"));
854
+ }
855
+
856
+ #[test]
857
+ fn binary_signature_is_not_called_magic_utf8() {
858
+ let temp = tempfile::tempdir().unwrap();
859
+ let path = temp.path().join("module.bin");
860
+ let mut file = File::create(&path).unwrap();
861
+ file.write_all(b"\0asm\x01\0\0\0").unwrap();
862
+
863
+ let mut opts = InspectOptions::new();
864
+ opts.run_id = Some("run_magic".into());
865
+ opts.externalize = false;
866
+ let receipt = inspect_path_with_options(temp.path(), opts).unwrap();
867
+ let fact = receipt.facts.first().unwrap();
868
+ assert_eq!(fact.content.kind, "binary");
869
+ assert_eq!(fact.content.signature.as_deref(), Some("wasm"));
870
+ assert!(fact.content.encoding.is_none());
871
+ assert_eq!(fact.source.type_id, "unknown");
872
+ }
873
+
874
+ #[test]
875
+ fn church_site_fixture_produces_semantic_perception() {
876
+ let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
877
+ .join("../../../apps/client-cms-editor/fixtures/donor-themes/church-site");
878
+ assert!(
879
+ fixture.join("site/index.html").exists(),
880
+ "church-site fixture missing at {}",
881
+ fixture.display()
882
+ );
883
+
884
+ let mut opts = InspectOptions::new();
885
+ opts.run_id = Some("run_church".into());
886
+ // Keep full facts in-memory for assertions; still exercise enrichment.
887
+ opts.externalize = false;
888
+ let receipt = inspect_path_with_options(&fixture, opts).unwrap();
889
+
890
+ let html = receipt
891
+ .facts
892
+ .iter()
893
+ .filter(|f| f.source.type_id == "html")
894
+ .count();
895
+ let svg = receipt
896
+ .facts
897
+ .iter()
898
+ .filter(|f| f.source.type_id == "svg")
899
+ .count();
900
+ let json = receipt
901
+ .facts
902
+ .iter()
903
+ .filter(|f| f.source.type_id == "json")
904
+ .count();
905
+
906
+ assert_eq!(html, 5, "expected 5 HTML pages");
907
+ assert_eq!(svg, 9, "expected 9 SVG assets");
908
+ assert_eq!(json, 1, "expected theme.json");
909
+ assert!(receipt.edges.len() > 0, "edges must not be empty");
910
+ assert!(receipt.findings.len() > 0, "findings must not be empty");
911
+ assert!(receipt.artifacts.len() > 0, "artifacts must not be empty");
912
+
913
+ assert!(receipt
914
+ .findings
915
+ .iter()
916
+ .any(|f| f.get("kind") == Some(&serde_json::json!("theme_manifest_candidate"))
917
+ || f.get("observation") == Some(&serde_json::json!("theme_manifest"))));
918
+ assert!(receipt
919
+ .findings
920
+ .iter()
921
+ .any(|f| f.get("kind") == Some(&serde_json::json!("composition"))
922
+ || f.get("observation") == Some(&serde_json::json!("html_documents"))));
923
+ assert!(!receipt.edges.iter().any(|e| {
924
+ e.get("type") == Some(&serde_json::json!("theme_applies_to"))
925
+ }));
926
+ assert!(receipt
927
+ .artifacts
928
+ .iter()
929
+ .any(|a| a.get("kind") == Some(&serde_json::json!("route_manifest"))
930
+ || a.get("kind") == Some(&serde_json::json!("asset_manifest"))));
931
+ assert!(receipt.edges.iter().any(|e| {
932
+ e.get("type") == Some(&serde_json::json!("asset_reference"))
933
+ && e
934
+ .pointer("/evidence/literal")
935
+ .and_then(|v| v.as_str())
936
+ .is_some_and(|s| s.starts_with("https://"))
937
+ }));
938
+ assert!(!receipt.provenance.network_used);
939
+
940
+ for finding in &receipt.findings {
941
+ let has_support = finding.get("evidence").is_some()
942
+ || finding.get("observations").is_some()
943
+ || finding.get("composition").is_some();
944
+ assert!(
945
+ has_support,
946
+ "finding missing evidence/observations/composition: {finding}"
947
+ );
948
+ }
949
+
950
+ let beliefs = receipt
951
+ .facts
952
+ .iter()
953
+ .find(|f| f.path == "site/beliefs.html")
954
+ .unwrap();
955
+ assert_eq!(beliefs.fs_kind, "file");
956
+ assert_eq!(beliefs.source.type_id, "html");
957
+ assert_eq!(beliefs.classification.role, "page_candidate");
958
+ assert!(!beliefs.classification.generated);
959
+ assert_eq!(beliefs.content.encoding.as_deref(), Some("utf-8"));
960
+ assert!(beliefs.content.signature.is_none());
961
+ // analysis.cache_hit is execution provenance, not "this file is cache content"
962
+ assert!(!beliefs.analysis.cache_hit || receipt.provenance.cache.hits > 0);
963
+
964
+ assert_graph_edge_ids_unique(&receipt.edges);
965
+ }
966
+
967
+ #[test]
968
+ fn single_file_inspect_externalizes_under_parent_not_file() {
969
+ let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join(
970
+ "../../../apps/client-cms-editor/fixtures/frontend-perception/page.tsx",
971
+ );
972
+ assert!(fixture.exists(), "missing fixture {}", fixture.display());
973
+
974
+ let mut opts = InspectOptions::new();
975
+ opts.run_id = Some("run_single_file".into());
976
+ opts.externalize = true;
977
+ let receipt = inspect_path_with_options(&fixture, opts).unwrap();
978
+
979
+ assert_eq!(receipt.stats.files, 1);
980
+ assert!(receipt.facts.iter().any(|f| f.path.ends_with("page.tsx")));
981
+ assert!(
982
+ receipt
983
+ .inputs
984
+ .get("content_root")
985
+ .is_some_and(|r| Path::new(r).is_dir()),
986
+ "content_root must be a directory"
987
+ );
988
+ let artifact_dir = receipt
989
+ .detail
990
+ .as_ref()
991
+ .and_then(|d| d.get("artifact_dir"))
992
+ .and_then(|v| v.as_str())
993
+ .expect("artifact_dir");
994
+ assert!(
995
+ artifact_dir.contains("/.agentsam/machine/runs/"),
996
+ "unexpected artifact_dir: {artifact_dir}"
997
+ );
998
+ assert!(
999
+ !artifact_dir.contains("page.tsx/.agentsam"),
1000
+ "must not nest .agentsam under the file path: {artifact_dir}"
1001
+ );
1002
+ assert!(Path::new(artifact_dir).is_dir());
1003
+ }
1004
+
1005
+ #[test]
1006
+ fn frontend_perception_page_tsx_emits_generic_candidates() {
1007
+ let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join(
1008
+ "../../../apps/client-cms-editor/fixtures/frontend-perception/page.tsx",
1009
+ );
1010
+ let mut opts = InspectOptions::new();
1011
+ opts.run_id = Some("run_frontend_perception".into());
1012
+ opts.externalize = false;
1013
+ let receipt = inspect_path_with_options(&fixture, opts).unwrap();
1014
+
1015
+ let finding = receipt
1016
+ .findings
1017
+ .iter()
1018
+ .find(|f| f.get("kind") == Some(&serde_json::json!("frontend_source_candidates")))
1019
+ .expect("frontend_source_candidates finding");
1020
+ let candidates = finding.get("candidates").expect("candidates");
1021
+ let routes = candidates
1022
+ .get("route_candidate")
1023
+ .and_then(|v| v.as_array())
1024
+ .expect("route_candidate");
1025
+ assert!(
1026
+ routes.iter().any(|r| r.as_str() == Some("/")),
1027
+ "expected slug / in routes: {routes:?}"
1028
+ );
1029
+ assert!(routes.iter().any(|r| r.as_str() == Some("/work")));
1030
+
1031
+ let shells = candidates
1032
+ .get("shell_candidate")
1033
+ .and_then(|v| v.as_array())
1034
+ .expect("shell_candidate");
1035
+ for zone in ["HEADER", "BODY", "FOOTER"] {
1036
+ assert!(
1037
+ shells.iter().any(|s| s.as_str() == Some(zone)),
1038
+ "missing shell zone {zone}"
1039
+ );
1040
+ }
1041
+
1042
+ let sections = candidates
1043
+ .get("section_candidate")
1044
+ .and_then(|v| v.as_array())
1045
+ .expect("section_candidate");
1046
+ assert!(
1047
+ sections.iter().any(|s| {
1048
+ s.get("type").and_then(|t| t.as_str()) == Some("Hero")
1049
+ && s.get("zone").and_then(|z| z.as_str()) == Some("BODY")
1050
+ }),
1051
+ "expected Hero BODY section candidate: {sections:?}"
1052
+ );
1053
+
1054
+ let tokens = candidates
1055
+ .get("design_token_evidence")
1056
+ .and_then(|v| v.as_array())
1057
+ .expect("design_token_evidence");
1058
+ assert!(tokens.iter().any(|t| {
1059
+ t.as_str()
1060
+ .is_some_and(|s| s.starts_with("--") || s.starts_with('#'))
1061
+ }));
1062
+
1063
+ // Must stay generic — no CMS identity productization in Machine.
1064
+ let blob = serde_json::to_string(&receipt.findings).unwrap();
1065
+ assert!(!blob.contains("hero.cinematic"));
1066
+ assert!(!blob.contains("navigation.minimal"));
1067
+
1068
+ assert_graph_edge_ids_unique(&receipt.edges);
1069
+ }
1070
+
1071
+ fn assert_graph_edge_ids_unique(edges: &[Value]) {
1072
+ use std::collections::BTreeSet;
1073
+ let mut seen = BTreeSet::new();
1074
+ for edge in edges {
1075
+ let id = edge
1076
+ .get("id")
1077
+ .and_then(|v| v.as_str())
1078
+ .filter(|s| !s.is_empty())
1079
+ .unwrap_or_else(|| panic!("edge missing non-empty id: {edge}"));
1080
+ assert!(
1081
+ seen.insert(id.to_string()),
1082
+ "duplicate edge id: {id}"
1083
+ );
1084
+ }
1085
+ }
1086
+ }