gennady 0.6.0 → 0.7.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.
- package/README.md +2 -15
- package/ai/agents/agent-resolve-conflicts.xml +6 -0
- package/ai/agents/agent-review-verifier.xml +6 -0
- package/ai/directives/architecture/README.md +21 -0
- package/ai/directives/coding/README.md +23 -0
- package/ai/directives/coding/result-conventions.xml +55 -0
- package/ai/directives/coding/svelte5-runes.xml +248 -0
- package/ai/directives/coding/sveltekit-rules.xml +247 -0
- package/ai/directives/coding/typescript-rules.xml +589 -0
- package/ai/directives/coding/uikit-component-storybook.xml +347 -0
- package/ai/directives/coding/uikit-component-svelte.xml +344 -0
- package/ai/directives/coding/uikit-spec-drafting.xml +243 -0
- package/ai/directives/dbc-audit.directive.xml +131 -0
- package/ai/directives/dev-review.directive.xml +148 -0
- package/ai/directives/infra/README.md +11 -0
- package/ai/directives/infra/eslint-setup.xml +467 -0
- package/ai/directives/infra/git-setup.xml +261 -0
- package/ai/directives/infra/nodejs-npm-setup.xml +354 -0
- package/ai/directives/infra/storybook-setup.xml +153 -0
- package/ai/directives/knowledge.xml +206 -0
- package/ai/directives/perf-auditor/perf-auditor.directive.xml +75 -0
- package/ai/directives/perf-auditor/rules/async-latency.xml +101 -0
- package/ai/directives/perf-auditor/rules/data-structures.xml +103 -0
- package/ai/directives/perf-auditor/rules/iteration-fusion.xml +96 -0
- package/ai/directives/perf-auditor/rules/memory-gc.xml +102 -0
- package/ai/directives/sdd/README.md +49 -0
- package/ai/directives/sdd/audit.directive.xml +543 -0
- package/ai/directives/sdd/discovery.directive.xml +824 -0
- package/ai/directives/sdd/fix.directive.xml +249 -0
- package/ai/directives/sdd/module-decomposition.directive.xml +666 -0
- package/ai/directives/sdd/phase-execution-protocol.xml +339 -0
- package/ai/directives/sdd/scaffold.directive.xml +717 -0
- package/ai/directives/sdd/setup.directive.xml +213 -0
- package/ai/directives/sdd/svelte-ui-discovery.directive.xml +263 -0
- package/ai/directives/semantic-change-extractor.directive.xml +99 -0
- package/ai/directives/testing/README.md +25 -0
- package/ai/directives/testing/common.xml +234 -0
- package/ai/directives/testing/node-test.xml +288 -0
- package/ai/directives/testing/playwright-cli.xml +199 -0
- package/ai/directives/testing/playwright-e2e.xml +292 -0
- package/ai/directives/testing/storybook-usage.xml +173 -0
- package/ai/directives/testing/svelte-testing.xml +237 -0
- package/ai/directives/testing/vitest-rules.xml +326 -0
- package/ai/docs/README.md +17 -0
- package/ai/docs/ai-icl.md +538 -0
- package/ai/docs/ai-priming.md +548 -0
- package/ai/docs/ai-prompt-formats.md +406 -0
- package/ai/docs/ai-promting.md +572 -0
- package/ai/drafts/DRAFT.md +120 -0
- package/ai/drafts/agent-devgen-class-from-description.rules.xml +123 -0
- package/ai/drafts/agent-typescript-devgen.v1.xml +303 -0
- package/ai/drafts/d.md +65 -0
- package/ai/drafts/music-posts.md +105 -0
- package/ai/fw/v1/architecture/blueprint-factory.xml +77 -0
- package/ai/fw/v1/core/mental-model.xml +50 -0
- package/ai/fw/v1/discovery/intent-reactor.xml +92 -0
- package/ai/fw/v1/production/swarm-protocol.xml +122 -0
- package/ai/fw/v1/review/quality-pipeline.xml +102 -0
- package/ai/fw/v2/arch-universal.xml +73 -0
- package/ai/fw-draft/README.md +79 -0
- package/ai/fw-draft/bin/discovery.sh +116 -0
- package/ai/fw-draft/gennady.xml +58 -0
- package/ai/fw-draft/provider/claude.xml +16 -0
- package/ai/fw-draft/provider/cursor.xml +23 -0
- package/ai/fw-draft/provider/default.xml +12 -0
- package/ai/fw-draft/roles/developer.xml +18 -0
- package/ai/fw-draft/router.xml +39 -0
- package/ai/fw-draft/routes/development.xml +32 -0
- package/ai/fw-draft/routes/universal.xml +58 -0
- package/ai/fw-draft/rules/dev/base/file-structure-rules.xml +89 -0
- package/ai/fw-draft/rules/dev/typescript/contacts.xml +194 -0
- package/dist/ai/agents/agent-resolve-conflicts.xml +6 -0
- package/dist/ai/agents/agent-review-verifier.xml +6 -0
- package/dist/ai/directives/architecture/README.md +21 -0
- package/dist/ai/directives/coding/README.md +23 -0
- package/dist/ai/directives/coding/result-conventions.xml +55 -0
- package/dist/ai/directives/coding/svelte5-runes.xml +248 -0
- package/dist/ai/directives/coding/sveltekit-rules.xml +247 -0
- package/dist/ai/directives/coding/typescript-rules.xml +589 -0
- package/dist/ai/directives/coding/uikit-component-storybook.xml +347 -0
- package/dist/ai/directives/coding/uikit-component-svelte.xml +344 -0
- package/dist/ai/directives/coding/uikit-spec-drafting.xml +243 -0
- package/dist/ai/directives/dbc-audit.directive.xml +131 -0
- package/dist/ai/directives/dev-review.directive.xml +148 -0
- package/dist/ai/directives/infra/README.md +11 -0
- package/dist/ai/directives/infra/eslint-setup.xml +467 -0
- package/dist/ai/directives/infra/git-setup.xml +261 -0
- package/dist/ai/directives/infra/nodejs-npm-setup.xml +354 -0
- package/dist/ai/directives/infra/storybook-setup.xml +153 -0
- package/dist/ai/directives/knowledge.xml +206 -0
- package/dist/ai/directives/perf-auditor/perf-auditor.directive.xml +75 -0
- package/dist/ai/directives/perf-auditor/rules/async-latency.xml +101 -0
- package/dist/ai/directives/perf-auditor/rules/data-structures.xml +103 -0
- package/dist/ai/directives/perf-auditor/rules/iteration-fusion.xml +96 -0
- package/dist/ai/directives/perf-auditor/rules/memory-gc.xml +102 -0
- package/dist/ai/directives/sdd/README.md +49 -0
- package/dist/ai/directives/sdd/audit.directive.xml +543 -0
- package/dist/ai/directives/sdd/discovery.directive.xml +824 -0
- package/dist/ai/directives/sdd/fix.directive.xml +249 -0
- package/dist/ai/directives/sdd/module-decomposition.directive.xml +666 -0
- package/dist/ai/directives/sdd/phase-execution-protocol.xml +339 -0
- package/dist/ai/directives/sdd/scaffold.directive.xml +717 -0
- package/dist/ai/directives/sdd/setup.directive.xml +213 -0
- package/dist/ai/directives/sdd/svelte-ui-discovery.directive.xml +263 -0
- package/dist/ai/directives/semantic-change-extractor.directive.xml +99 -0
- package/dist/ai/directives/testing/README.md +25 -0
- package/dist/ai/directives/testing/common.xml +234 -0
- package/dist/ai/directives/testing/node-test.xml +288 -0
- package/dist/ai/directives/testing/playwright-cli.xml +199 -0
- package/dist/ai/directives/testing/playwright-e2e.xml +292 -0
- package/dist/ai/directives/testing/storybook-usage.xml +173 -0
- package/dist/ai/directives/testing/svelte-testing.xml +237 -0
- package/dist/ai/directives/testing/vitest-rules.xml +326 -0
- package/dist/ai/docs/README.md +17 -0
- package/dist/ai/docs/ai-icl.md +538 -0
- package/dist/ai/docs/ai-priming.md +548 -0
- package/dist/ai/docs/ai-prompt-formats.md +406 -0
- package/dist/ai/docs/ai-promting.md +572 -0
- package/dist/ai/drafts/DRAFT.md +120 -0
- package/dist/ai/drafts/agent-devgen-class-from-description.rules.xml +123 -0
- package/dist/ai/drafts/agent-typescript-devgen.v1.xml +303 -0
- package/dist/ai/drafts/d.md +65 -0
- package/dist/ai/drafts/music-posts.md +105 -0
- package/dist/ai/fw/v1/architecture/blueprint-factory.xml +77 -0
- package/dist/ai/fw/v1/core/mental-model.xml +50 -0
- package/dist/ai/fw/v1/discovery/intent-reactor.xml +92 -0
- package/dist/ai/fw/v1/production/swarm-protocol.xml +122 -0
- package/dist/ai/fw/v1/review/quality-pipeline.xml +102 -0
- package/dist/ai/fw/v2/arch-universal.xml +73 -0
- package/dist/ai/fw-draft/README.md +79 -0
- package/dist/ai/fw-draft/bin/discovery.sh +116 -0
- package/dist/ai/fw-draft/gennady.xml +58 -0
- package/dist/ai/fw-draft/provider/claude.xml +16 -0
- package/dist/ai/fw-draft/provider/cursor.xml +23 -0
- package/dist/ai/fw-draft/provider/default.xml +12 -0
- package/dist/ai/fw-draft/roles/developer.xml +18 -0
- package/dist/ai/fw-draft/router.xml +39 -0
- package/dist/ai/fw-draft/routes/development.xml +32 -0
- package/dist/ai/fw-draft/routes/universal.xml +58 -0
- package/dist/ai/fw-draft/rules/dev/base/file-structure-rules.xml +89 -0
- package/dist/ai/fw-draft/rules/dev/typescript/contacts.xml +194 -0
- package/dist/chunks/devtools-B-7ugZhF.js +79 -0
- package/dist/chunks/{help.cmd-CWasx25o.js → help.cmd-B_G7EWzF.js} +9 -2
- package/dist/chunks/{index-B63fYXL2.js → index-BeL1Zcbg.js} +1 -1
- package/dist/chunks/index-CVR66voe.js +26963 -0
- package/dist/chunks/index-CXuhZzS3.js +16979 -0
- package/dist/chunks/{index-B5bA2T7A.js → index-CaahtXiM.js} +33 -9
- package/dist/chunks/{index-iqg0w_pE.js → index-CiEM-8nJ.js} +35 -19
- package/dist/chunks/{index-B4m0-PAT.js → index-D1qsi0Uc.js} +57 -33
- package/dist/chunks/index-D9ceRUyB.js +443 -0
- package/dist/chunks/index-DJpVmyp2.js +176 -0
- package/dist/chunks/{index-C0andxna.js → index-DU6jD7SS.js} +1 -1
- package/dist/chunks/index-KxSZKmZn.js +540 -0
- package/dist/chunks/{index-Dqe1TdW4.js → index-UbHoePfr.js} +12 -12
- package/dist/chunks/{index-5xIgwwKx.js → index-g1LXlp77.js} +2 -2
- package/dist/chunks/index-zBnnuvLA.js +3788 -0
- package/dist/chunks/{run-review-command.logic-a_M3CkeZ.js → run-review-command.logic-DpkRoEi8.js} +2 -2
- package/dist/chunks/services-CaLOhuLV.js +2889 -0
- package/dist/chunks/shared-Bjy30TeM.js +665 -0
- package/dist/cli/cmd/_shared/prompt/io/load-agent-template.io.d.ts +3 -3
- package/dist/cli/cmd/_shared/prompt/logic/build-ai-first-knowledge-block.logic.d.ts +3 -3
- package/dist/cli/cmd/_shared/prompt/logic/build-ai-verify-placeholders.logic.d.ts +7 -4
- package/dist/cli/cmd/_shared/prompt/logic/verify-commands/resolve-verify-commands.logic.d.ts +5 -0
- package/dist/cli/cmd/_shared/update-check-worker.d.ts +1 -0
- package/dist/cli/cmd/_shared/update-check.d.ts +38 -0
- package/dist/cli/cmd/agent-mon/cmd/create-providers.d.ts +15 -0
- package/dist/cli/cmd/agent-mon/cmd/index.d.ts +1 -0
- package/dist/cli/cmd/agent-mon/cmd/run.d.ts +12 -0
- package/dist/cli/cmd/agent-mon/state/create-state-manager.d.ts +32 -0
- package/dist/cli/cmd/agent-mon/state/group-by-provider.d.ts +14 -0
- package/dist/cli/cmd/agent-mon/state/index.d.ts +5 -0
- package/dist/cli/cmd/agent-mon/state/is-waiting.d.ts +9 -0
- package/dist/cli/cmd/agent-mon/state/view-model.type.d.ts +74 -0
- package/dist/cli/cmd/agent-mon/ui/app.d.ts +16 -0
- package/dist/cli/cmd/agent-mon/ui/column-view.d.ts +14 -0
- package/dist/cli/cmd/agent-mon/ui/index.d.ts +10 -0
- package/dist/cli/cmd/agent-mon/ui/provider-column.d.ts +14 -0
- package/dist/cli/cmd/agent-mon/ui/session-card.d.ts +12 -0
- package/dist/cli/cmd/agent-mon/ui/status-badge.d.ts +10 -0
- package/dist/cli/cmd/alt-opinion/alt-opinion-parser.d.ts +18 -0
- package/dist/cli/cmd/alt-opinion/alt-opinion-runner.d.ts +32 -0
- package/dist/cli/cmd/alt-opinion/alt-opinion.cmd.d.ts +34 -0
- package/dist/cli/cmd/alt-opinion/alt-opinion.types.d.ts +88 -0
- package/dist/cli/cmd/alt-opinion/index.d.ts +1 -0
- package/dist/cli/cmd/cat/cat-url.fn.d.ts +19 -0
- package/dist/cli/cmd/lint/checks/anchor.check.d.ts +11 -0
- package/dist/cli/cmd/lint/checks/dbc-contract.check.d.ts +16 -0
- package/dist/cli/cmd/lint/checks/disables.check.d.ts +12 -0
- package/dist/cli/cmd/lint/checks/file-header.check.d.ts +10 -0
- package/dist/cli/cmd/lint/checks/language.check.d.ts +11 -0
- package/dist/cli/cmd/lint/index.d.ts +1 -0
- package/dist/cli/cmd/lint/lint.cmd.d.ts +18 -0
- package/dist/cli/cmd/lint/lint.types.d.ts +72 -0
- package/dist/cli/cmd/lint/utils/resolve-references.fn.d.ts +32 -0
- package/dist/cli/cmd/remote-console/index.d.ts +2 -0
- package/dist/cli/cmd/remote-console/remote-console.cmd.d.ts +55 -0
- package/dist/cli/cmd/resolve-conflicts/_core/io/resolve-conflicts-template-load.io.d.ts +2 -2
- package/dist/cli/cmd/resolve-conflicts/_core/logic/resolve-conflicts-command-args-parse.logic.d.ts +3 -3
- package/dist/cli/cmd/resolve-conflicts/_core/logic/resolve-conflicts-command-run.logic.d.ts +3 -3
- package/dist/cli/cmd/resolve-conflicts/_core/logic/resolve-conflicts-context-git-build.logic.d.ts +4 -4
- package/dist/cli/cmd/resolve-conflicts/_core/types/resolve-conflicts-artifact.type.d.ts +3 -1
- package/dist/cli/cmd/resolve-conflicts/_core/types/resolve-conflicts-command-args.type.d.ts +3 -1
- package/dist/cli/cmd/resolve-conflicts/_core/types/resolve-conflicts-command-result.type.d.ts +5 -1
- package/dist/cli/cmd/resolve-conflicts/_core/types/resolve-conflicts-context-git.type.d.ts +18 -2
- package/dist/cli/cmd/resolve-conflicts/_core/xml/resolve-conflicts-artifact-build.xml.d.ts +6 -6
- package/dist/cli/cmd/resolve-conflicts/_core/xml/resolve-conflicts-render.xml.d.ts +4 -4
- package/dist/cli/cmd/review/_core/io/load-review-verify-template.io.d.ts +2 -2
- package/dist/cli/cmd/review/_core/logic/build-review-context-git.logic.d.ts +3 -3
- package/dist/cli/cmd/review/_core/logic/build-review-context-vcs.logic.d.ts +2 -2
- package/dist/cli/cmd/review/_core/logic/load-review-context-mr.logic.d.ts +5 -5
- package/dist/cli/cmd/review/_core/logic/parse-review-command-args.logic.d.ts +3 -3
- package/dist/cli/cmd/review/_core/logic/resolve-review-intent.logic.d.ts +3 -3
- package/dist/cli/cmd/review/_core/logic/run-review-command.logic.d.ts +3 -3
- package/dist/cli/cmd/review/_core/types/review-artifact.type.d.ts +4 -1
- package/dist/cli/cmd/review/_core/types/review-command-args.type.d.ts +7 -1
- package/dist/cli/cmd/review/_core/types/review-command-mode.type.d.ts +1 -1
- package/dist/cli/cmd/review/_core/types/review-command-options.type.d.ts +3 -1
- package/dist/cli/cmd/review/_core/types/review-command-result.type.d.ts +5 -1
- package/dist/cli/cmd/review/_core/types/review-context-git.type.d.ts +3 -1
- package/dist/cli/cmd/review/_core/types/review-context-mr.type.d.ts +22 -3
- package/dist/cli/cmd/review/_core/types/review-context-vcs.type.d.ts +4 -1
- package/dist/cli/cmd/review/_core/types/review-intent.type.d.ts +1 -1
- package/dist/cli/cmd/review/_core/xml/build-review-artifact.xml.d.ts +10 -10
- package/dist/cli/cmd/review/_core/xml/render-review-issues.xml.d.ts +3 -3
- package/dist/cli/cmd/review/_core/xml/render-review-verify.xml.d.ts +4 -4
- package/dist/cli/cmd/sync/index.d.ts +1 -0
- package/dist/cli/cmd/sync/sync-core.d.ts +65 -0
- package/dist/cli/cmd/sync/sync-formatter.d.ts +12 -0
- package/dist/cli/cmd/sync/sync.cmd.d.ts +33 -0
- package/dist/cli/cmd/sync/sync.types.d.ts +50 -0
- package/dist/cli/cmd/vcs-reply/vcs-reply.cmd.d.ts +4 -4
- package/dist/cli/utils/ai-legacy/ai-legacy-agent.d.ts +12 -11
- package/dist/cli/utils/ai-legacy/ai-legacy-core.d.ts +33 -17
- package/dist/cli/utils/ai-legacy/ai-legacy-model.d.ts +42 -23
- package/dist/cli/utils/cat-gen/cat-gen.d.ts +19 -8
- package/dist/cli/utils/commit-gen/commit-gen.d.ts +39 -15
- package/dist/cli/utils/prompts/index.d.ts +6 -6
- package/dist/cli/utils/review-gen/review-gen.d.ts +33 -9
- package/dist/gennady.js +30 -10
- package/dist/index.d.ts +1 -0
- package/dist/index.js +44 -23
- package/dist/services/agent-mon/diff/diff.d.ts +9 -0
- package/dist/services/agent-mon/diff/index.d.ts +1 -0
- package/dist/services/agent-mon/index.d.ts +10 -0
- package/dist/services/agent-mon/model/agent-provider.type.d.ts +20 -0
- package/dist/services/agent-mon/model/agent-session.type.d.ts +49 -0
- package/dist/services/agent-mon/model/errors.d.ts +20 -0
- package/dist/services/agent-mon/model/index.d.ts +7 -0
- package/dist/services/agent-mon/model/observe-opts.type.d.ts +7 -0
- package/dist/services/agent-mon/model/scan-opts.type.d.ts +7 -0
- package/dist/services/agent-mon/model/session-changes.type.d.ts +10 -0
- package/dist/services/agent-mon/monitor/agent-monitor.d.ts +44 -0
- package/dist/services/agent-mon/monitor/create-monitor.d.ts +6 -0
- package/dist/services/agent-mon/monitor/index.d.ts +2 -0
- package/dist/services/agent-mon/observe/index.d.ts +1 -0
- package/dist/services/agent-mon/observe/observe.d.ts +12 -0
- package/dist/services/agent-mon/providers/claude/claude-provider.d.ts +50 -0
- package/dist/services/agent-mon/providers/claude/index.d.ts +5 -0
- package/dist/services/agent-mon/providers/claude/ps.d.ts +36 -0
- package/dist/services/agent-mon/providers/claude/session-json.d.ts +37 -0
- package/dist/services/agent-mon/providers/opencode/db.d.ts +41 -0
- package/dist/services/agent-mon/providers/opencode/index.d.ts +3 -0
- package/dist/services/agent-mon/providers/opencode/model-parser.d.ts +6 -0
- package/dist/services/agent-mon/providers/opencode/opencode-provider.d.ts +45 -0
- package/dist/services/ai-client/providers/ai-model.type.d.ts +14 -0
- package/dist/services/ai-client/providers/open-router/open-router-model.type.d.ts +1 -4
- package/dist/services/ai-client/providers/open-router/open-router-provider.d.ts +17 -0
- package/dist/services/ai-client/providers/openai-like-provider.d.ts +1 -0
- package/dist/services/data-ore/telegram/telegram-data-ore.d.ts +17 -0
- package/dist/services/data-ore/telegram/telegram-data-ore.types.d.ts +4 -0
- package/dist/services/data-ore/telegram/telegram-demo-music-helper.d.ts +1 -0
- package/dist/services/data-ore/telegram/telegram-demo.d.ts +1 -0
- package/dist/services/dbc/linter/dbc-ast-adapter.types.d.ts +82 -0
- package/dist/services/dbc/linter/dbc-linter.types.d.ts +95 -0
- package/dist/services/dbc/linter/implementations/ts/dbc-ts-ast-adapter.d.ts +183 -0
- package/dist/services/dbc/linter/implementations/ts/dbc-ts-linter.d.ts +152 -0
- package/dist/services/dbc/parser/dbc-parser.types.d.ts +16 -16
- package/dist/services/dbc/parser/implementations/jsdoc/dbc-jsdoc-parser.d.ts +14 -4
- package/dist/services/logger/logger.d.ts +26 -6
- package/dist/services/remote-console/client/remote-console-client-serializer.d.ts +7 -0
- package/dist/services/remote-console/client/remote-console-client.d.ts +20 -0
- package/dist/services/remote-console/client/remote-console-client.types.d.ts +88 -0
- package/dist/services/remote-console/remote-console.d.ts +6 -0
- package/dist/services/remote-console/server/remote-console-server.d.ts +10 -0
- package/dist/services/remote-console/server/remote-console-server.types.d.ts +44 -0
- package/dist/services/remote-console/server/remote-console-stdout-writer.d.ts +26 -0
- package/dist/services/vcs-client/abstract/vcs-client-merge-discussions.d.ts +22 -14
- package/dist/services/vcs-client/abstract/vcs-client-merge-requests.d.ts +31 -14
- package/dist/services/vcs-client/abstract/vcs-client-repository-files.d.ts +16 -0
- package/dist/services/vcs-client/abstract/vcs-client.d.ts +9 -5
- package/dist/services/vcs-client/entities/vcs-file-content.type.d.ts +24 -0
- package/dist/services/vcs-client/entities/vcs-merge-request-changes.type.d.ts +32 -0
- package/dist/services/vcs-client/entities/vcs-url.type.d.ts +14 -0
- package/dist/services/vcs-client/entities/vcs-user.type.d.ts +3 -0
- package/dist/services/vcs-client/github/vcs-github-client.d.ts +31 -0
- package/dist/services/vcs-client/github/vcs-github-merge-requests.d.ts +40 -0
- package/dist/services/vcs-client/github/vcs-github-repository-files.d.ts +27 -0
- package/dist/services/vcs-client/gitlab/vcs-gitlab-client.d.ts +13 -4
- package/dist/services/vcs-client/gitlab/vcs-gitlab-merge-discussions.d.ts +16 -5
- package/dist/services/vcs-client/gitlab/vcs-gitlab-merge-requests.d.ts +24 -5
- package/dist/services/vcs-client/gitlab/vcs-gitlab-repository-files.d.ts +27 -0
- package/dist/services/vcs-client/parse-vcs-url.d.ts +3 -0
- package/dist/shared/backend/git/git-core.d.ts +24 -22
- package/dist/shared/backend/git/git-diff.d.ts +16 -5
- package/dist/shared/backend/rc/rc-config.d.ts +27 -15
- package/dist/shared/common/exec.d.ts +4 -6
- package/dist/shared/common/files.d.ts +1 -3
- package/dist/shared/common/language.d.ts +3 -6
- package/dist/shared/common/parse-args.d.ts +1 -4
- package/dist/shared/common/style.d.ts +3 -3
- package/dist/shared/common/think.d.ts +1 -5
- package/dist/shared/common/tokens.d.ts +1 -5
- package/dist/shared/common/unguard.d.ts +4 -8
- package/dist/shared/common/xml.d.ts +16 -12
- package/package.json +20 -4
- package/dist/.ai/agents/agent-review-verifier.xml +0 -181
- package/dist/chunks/index-CNbmXK8M.js +0 -3548
- package/dist/chunks/services-Sb7TwLxt.js +0 -122
- package/dist/chunks/shared-BgLzFWMH.js +0 -577
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# Log Driven Development
|
|
2
|
+
|
|
3
|
+
## Primary goal:
|
|
4
|
+
Получить свазнный AI Firendly логирование по которому мождно было воставнить что происходило с системой в виде некого аналогка call graph, чтобы получить какие методы вызывались, какие аргументы и результат.
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
## Example: OOP
|
|
8
|
+
```ts
|
|
9
|
+
import { LDD } from '#logger/ldd';
|
|
10
|
+
|
|
11
|
+
/** @purpose Creates URL-friendly slugs from strings. */
|
|
12
|
+
@LDD.class('Slugify')
|
|
13
|
+
export class Slugify {
|
|
14
|
+
/**
|
|
15
|
+
* @purpose Converts a string into a URL-friendly slug.
|
|
16
|
+
* @param text The input string to convert.
|
|
17
|
+
* @param options An optional object with configuration.
|
|
18
|
+
* @returns A promise that resolves to the generated slug.
|
|
19
|
+
* @throws {TessellError} Throws if the input `text` is not a non-empty string.
|
|
20
|
+
* @invariant The output will only contain lowercase alphanumeric characters and the delimiter.
|
|
21
|
+
*/
|
|
22
|
+
@LDD.method()
|
|
23
|
+
async create(text: string, options?: { delimiter?: string }): Promise<string> {
|
|
24
|
+
// START_CREATE_VALIDATE_INPUT
|
|
25
|
+
if (typeof text !== 'string' || text.length === 0) {
|
|
26
|
+
throw LDD.error({
|
|
27
|
+
state: `validate`,
|
|
28
|
+
error: new Error('Input text must be a non-empty string.', { cause: { text } }),
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
// END_CREATE_VALIDATE_INPUT
|
|
32
|
+
|
|
33
|
+
const delimiter = options?.delimiter ?? '-';
|
|
34
|
+
|
|
35
|
+
LDD.debug({state: 'transform'}).msg`Apply '${delimiter}' delimiter`;
|
|
36
|
+
|
|
37
|
+
// START_CREATE_APPLY_TRANSFORMATIONS
|
|
38
|
+
const slug = text
|
|
39
|
+
.toLowerCase()
|
|
40
|
+
.replace(/\s+/g, delimiter)
|
|
41
|
+
.replace(new RegExp(`[^a-z0-9${delimiter}]`, 'g'), '');
|
|
42
|
+
// END_CREATE_APPLY_TRANSFORMATIONS
|
|
43
|
+
|
|
44
|
+
return slug;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const slugify = new Slugify();
|
|
49
|
+
// LOG: [datetime] [debug] [Slugify#constructor] Instantiated {tid: <traceId>, args: <arguments>, time: <ms>}
|
|
50
|
+
|
|
51
|
+
const result = await slugify.create() ;
|
|
52
|
+
// LOG: [datetime] [debug] [Slugify#create] [idle → invoked] {tid: <traceId>, args: <redacted arguments>}
|
|
53
|
+
// LOG: [datetime] [error] [Slugify#create] [invoked → validate] {tid: <traceId>, error, time: <ms>}
|
|
54
|
+
|
|
55
|
+
const result = await slugify.create('...') ;
|
|
56
|
+
// LOG: [datetime] [debug] [Slugify#create] [idle → invoked] {tid: <traceId>, args: <redacted arguments>}
|
|
57
|
+
// LOG: [datetime] [debug] [Slugify#create] [invoked → transform] Apply '-' delimiter {tid: <traceId>, time: <ms>}
|
|
58
|
+
// LOG: [datetime] [debug] [Slugify#create] [transform → returns] {tid: <traceId>, returns: <redacted value>, time: <ms>}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Example: Functional
|
|
62
|
+
```ts
|
|
63
|
+
import { LDD } from '#logger/ldd';
|
|
64
|
+
|
|
65
|
+
/** @purpose Конфигурация для выбора стратегии обработки. */
|
|
66
|
+
export type DecideStrategyConfig = {
|
|
67
|
+
/** @purpose Путь к целевому ресурсу (если отсутствует, используется fallback). */
|
|
68
|
+
path?: string;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* @purpose Определяет стратегию обработки на основе наличия пути в конфигурации.
|
|
73
|
+
* @param config Параметры конфигурации.
|
|
74
|
+
* @returns Идентификатор выбранной стратегии.
|
|
75
|
+
*/
|
|
76
|
+
@LDD.fn('decideStrategy')
|
|
77
|
+
export function decideStrategy(config: DecideStrategyConfig): string {
|
|
78
|
+
if (!config?.path) {
|
|
79
|
+
return LDD.warn({
|
|
80
|
+
state: 'fallback',
|
|
81
|
+
returnValue: './',
|
|
82
|
+
}).msg`No 'config.path' provided`;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return 'primary';
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
decideStrategy();
|
|
89
|
+
// LOG: [datetime] [debug] [decideStrategy] [idle → invoked] {tid: <traceId>, args: <redacted arguments>}
|
|
90
|
+
// LOG: [datetime] [debug] [decideStrategy] [invoked → fallback] No 'config.path' provided {tid: <traceId>, returns: <redacted returnValue>}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## API
|
|
94
|
+
|
|
95
|
+
### `@LDD.class`
|
|
96
|
+
ЦЕЛЬ: Добавить в класс свойсиво `LDD_SYMBOL` (если его нет) равный экземпляру `LDD.Logger(<name>, LDD.active)`, так же модифицировать `constructor` (чтобы добавить логгирование), по факту выпонить LDD.method для него.
|
|
97
|
+
|
|
98
|
+
### `@LDD.method`
|
|
99
|
+
Обернуть метод класса в try catch и выставлять сохраняет текущий `LDD.active` и выставляет новый на время работы метода.
|
|
100
|
+
|
|
101
|
+
### `@LDD.fn`
|
|
102
|
+
Аналогично `LDD.method`, но для произвольной функции.
|
|
103
|
+
|
|
104
|
+
### `LOG.debug/info/warn/error`
|
|
105
|
+
Методы логирования которые формируют лог на основе `LDD.active`
|
|
106
|
+
|
|
107
|
+
### `LDD.active`
|
|
108
|
+
Активный контекст логирования, Он должен участвовать не только в выводе лога, но и добавляться в контекст, который структурный выводится вторым аргументом влоги. И добавлять туда... Добавлять туда индификатор с связанной записи. Это должен быть TID.
|
|
109
|
+
|
|
110
|
+
ВАЖНО: Также, если у нас происходит варнинг или ошибка, то должно сразу же выводиться как бы под логом еще записи в виде колтрейса. Вот как раз под цепочки TID нужно поднять всю цепочку записи, чтобы можно было показать цепочку вызовов.
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
**Active Moni
|
|
114
|
+
```
|
|
115
|
+
app:
|
|
116
|
+
stats:
|
|
117
|
+
- CPU: 10% (current), 5% (avg), 3% (min), 50% (max)
|
|
118
|
+
- Working Memory: 800M (current), 500M (avg), 200M (min), 800M (max)
|
|
119
|
+
- <другие метрики, например Peak Working Memory>
|
|
120
|
+
```
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
<AgentInitialPrompt id="DevGenClassFromDescription" keywords="utility_class:10 self_contained_code:9 code_generation:8" hint="Full instruction set for an AI agent to generate utility classes from a description.">
|
|
2
|
+
<Role>
|
|
3
|
+
You are an AI Developer creating code for an ecosystem where the primary consumers and modifiers of your code are other AI agents and AI-powered IDE tools. You are an architect of machine-readable and machine-modifiable code.
|
|
4
|
+
</Role>
|
|
5
|
+
<PrimaryGoal>
|
|
6
|
+
To create a **self-contained, ready-to-use class** based on a textual description. The generated code must be **AI-first**: maximally structured, semantically tagged, and predictable for automated analysis and modification.
|
|
7
|
+
</PrimaryGoal>
|
|
8
|
+
<BeliefState hint="A set of fundamental beliefs.">
|
|
9
|
+
<Belief name="Structure is everything">
|
|
10
|
+
**Structure is everything:** AI tools process code as a structure, not as plain text. Explicit tagging (via anchors, types, decorators) is superior to any implicit convention.
|
|
11
|
+
</Belief>
|
|
12
|
+
<Belief name="Predictability is contract with machine">
|
|
13
|
+
**Predictability is a contract with the machine:** The system must operate under absolute rules. The `@instrument` decorator is a strict protocol for handling operations, allowing no exceptions.
|
|
14
|
+
</Belief>
|
|
15
|
+
<Belief name="Intention is api for refactoring">
|
|
16
|
+
**Intention is the API for refactoring:** AI anchors are not comments for humans. They are an API you provide to other AIs for precise and safe code modification.
|
|
17
|
+
</Belief>
|
|
18
|
+
</BeliefState>
|
|
19
|
+
<GoldenExample hint="The canonical example of generating a class from a description.">
|
|
20
|
+
<Purpose>Below is an example of a user's request and the ideal implementation based on it. Your generated code must be identical to this example in structure, style, and level of detail.</Purpose>
|
|
21
|
+
<InputDescription hint="An example of a user's task description.">
|
|
22
|
+
Create a utility class `Slugify`.
|
|
23
|
+
It must have one public method `create(text: string, options?: { delimiter?: string }): string`.
|
|
24
|
+
This method must convert the input string into a URL-friendly "slug".
|
|
25
|
+
It should lowercase the text, replace spaces with a delimiter (defaulting to '-'), and remove any characters that are not alphanumeric or the delimiter.
|
|
26
|
+
</InputDescription>
|
|
27
|
+
<Source file="slugify.ts" hint="The ideal generated implementation.">
|
|
28
|
+
import { MainLogger } from "@core/logger/ldd";
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @purpose Creates URL-friendly slugs from strings.
|
|
32
|
+
* @behavior Stateless utility class with pure function logic.
|
|
33
|
+
*/
|
|
34
|
+
export class Slugify {
|
|
35
|
+
/** @purpose Logger for structured observability (trace, errors) within this class. */
|
|
36
|
+
protected _logger = MainLogger;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @purpose Converts a string into a URL-friendly slug.
|
|
40
|
+
* @param text The input string to convert.
|
|
41
|
+
* @param options An optional object with configuration.
|
|
42
|
+
* @returns A promise that resolves to the generated slug.
|
|
43
|
+
* @throws {TessellError} Throws if the input `text` is not a non-empty string.
|
|
44
|
+
* @invariant The output will only contain lowercase alphanumeric characters and the delimiter.
|
|
45
|
+
*/
|
|
46
|
+
async create(text: string, options?: { delimiter?: string }): Promise<string> {
|
|
47
|
+
this._logger.debug(`[Slugify#create] [idle → validate]`, {args: {text, options}});
|
|
48
|
+
|
|
49
|
+
// START_CREATE_VALIDATE_INPUT
|
|
50
|
+
if (typeof text !== 'string' || text.length === 0) {
|
|
51
|
+
const error = new TessellError(
|
|
52
|
+
"[Slugify#create] Input text must be a non-empty string.",
|
|
53
|
+
{ cause: { text } },
|
|
54
|
+
);
|
|
55
|
+
this._logger.error(`[Slugify#create] [validate → failed]`, error);
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
// END_CREATE_VALIDATE_INPUT
|
|
59
|
+
|
|
60
|
+
const delimiter = options?.delimiter ?? '-';
|
|
61
|
+
|
|
62
|
+
this._logger.debug(`[Slugify#create] [validate → transform] Apply "${delimiter}" delimiter`);
|
|
63
|
+
|
|
64
|
+
// START_CREATE_APPLY_TRANSFORMATIONS
|
|
65
|
+
const slug = text
|
|
66
|
+
.toLowerCase()
|
|
67
|
+
.replace(/\s+/g, delimiter)
|
|
68
|
+
.replace(new RegExp(`[^a-z0-9${delimiter}]`, 'g'), '');
|
|
69
|
+
// END_CREATE_APPLY_TRANSFORMATIONS
|
|
70
|
+
|
|
71
|
+
this._logger.info(`[Slugify#create] [transform → ok]`, {result: slug});
|
|
72
|
+
|
|
73
|
+
return slug;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
</Source>
|
|
77
|
+
</GoldenExample>
|
|
78
|
+
<Guidelines hint="Guiding Principles.">
|
|
79
|
+
<Purpose>To achieve the goal of creating AI-first code, you must follow these principles.</Purpose>
|
|
80
|
+
<Principle name="English First, Semantically Dense">
|
|
81
|
+
- **Essence:** All generated code, including JSDoc, comments, and log messages, must be in **English**.
|
|
82
|
+
- **Consequence:** Your language must be semantically dense: convey the maximum meaning with the minimum number of tokens. Be clear, concise, and unambiguous.
|
|
83
|
+
</Principle>
|
|
84
|
+
<Principle name="The Description is the Contract">
|
|
85
|
+
- **Essence:** The user-provided text description is the absolute and single source of truth for the class's public API.
|
|
86
|
+
- **Consequence:** You must precisely implement all requirements from the description: class name, method names, their parameters, and return types. The JSDoc must fully document each public member.
|
|
87
|
+
</Principle>
|
|
88
|
+
<Principle name="Declarative Behavior">
|
|
89
|
+
- **Essence:** Repetitive boilerplate code (logging, try/catch) must be replaced by declarative tools.
|
|
90
|
+
- **Consequence:** You must use the `@instrument` decorator for all public methods to delegate observability and error handling tasks.
|
|
91
|
+
</Principle>
|
|
92
|
+
</Guidelines>
|
|
93
|
+
<Rulebook hint="Implementation Rulebook.">
|
|
94
|
+
<Purpose>This is your core set of technical requirements. Each point is mandatory.</Purpose>
|
|
95
|
+
<Rule name="JSDoc Contract">
|
|
96
|
+
- **Class JSDoc:** Must contain `@purpose` (what the class does). It may contain an optional `@behavior` tag to describe key characteristics (e.g., "stateless", "immutable") only if it provides information not obvious from the purpose.
|
|
97
|
+
- **Method JSDoc:** Must be a complete contract, including:
|
|
98
|
+
- `@purpose`: What the method does.
|
|
99
|
+
- `@param`: For each parameter.
|
|
100
|
+
- `@returns`: The resolved value of the promise.
|
|
101
|
+
- `@throws`: (Optional) The type of error thrown on failure.
|
|
102
|
+
- `@invariant`: (Optional) A condition, pre-condition, or post-condition that is always true.
|
|
103
|
+
</Rule>
|
|
104
|
+
<Rule name="AI Intent Anchors">
|
|
105
|
+
- **Format:** Use **only paired** anchors (`// START_...` / `// END_...`).
|
|
106
|
+
- **Coverage:** Every logical block of business logic must be wrapped in anchors. Simple variable assignments do not need to be wrapped.
|
|
107
|
+
</Rule>
|
|
108
|
+
<Rule name="Error Handling and Observability">
|
|
109
|
+
- **Decorator `@instrument`:** All `try...catch` logic, basic logging, and error handling is delegated to the `@instrument` decorator.
|
|
110
|
+
- **Mandatory Usage:** **Every** public method **must** be decorated with `@instrument`.
|
|
111
|
+
- **Method Body:** The method body must not contain a `try...catch` block. Synchronous checks should `throw new TessellError(...)`.
|
|
112
|
+
</Rule>
|
|
113
|
+
<Rule name="Code Style (TypeScript for Native JS)">
|
|
114
|
+
- **Access Modifiers:**
|
|
115
|
+
- **`public`:** Do **not** use the `public` keyword. The absence of a modifier is the standard.
|
|
116
|
+
- **`private` and `#`:** Avoid `private` and native private fields (`#`). These create opaque objects that resist metaprogramming tools like decorators.
|
|
117
|
+
- **`protected`:** **Always use `protected`** for all non-public members. This is our standard for encapsulation, ensuring introspectability for tooling while hiding details from public consumption.
|
|
118
|
+
- **Naming:** All `protected` members must be prefixed with an underscore (`_`). Example: `protected _logger`.
|
|
119
|
+
- **Constructor Properties:** Do **not** use parameter properties shorthand. Properties must be explicitly declared in the class body. This aligns with native JavaScript class syntax and improves readability.
|
|
120
|
+
- **`enum`:** Do **not** use TypeScript `enum`s. Use string literal union types (`'type1' | 'type2'`) instead. They are a zero-cost abstraction that is fully erased at compile time, unlike `enum`s which generate JavaScript objects and are not natively supported by Node.js.
|
|
121
|
+
</Rule>
|
|
122
|
+
</Rulebook>
|
|
123
|
+
</AgentInitialPrompt>
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
<Agent_Configuration id="TYPESCRIPT_DEVGEN_V1" type="System_Prompt">
|
|
2
|
+
<Target_Objective>
|
|
3
|
+
Создать "Исполняемую спецификацию": универсальный TypeScript код, где синтаксис безупречен, а логика и намерения (Intent) кристаллизованы через структурные якоря и строгие JSDoc-контракты. Следующий AI-агент должен понять контекст и бизнес-логику кода с первого прочтения, без доступа к истории чата.
|
|
4
|
+
</Target_Objective>
|
|
5
|
+
<Role>
|
|
6
|
+
Ты — AI-Архитектор машиночитаемого кода (DevGen). Твой код будут читать, парсить и модифицировать ТОЛЬКО другие ИИ-агенты и AI-IDE (экосистема AI-to-AI).
|
|
7
|
+
Твоя высшая ценность — абсолютная предсказуемость, семантическая плотность и интроспективность кода.
|
|
8
|
+
Твоя базовая аксиома: "English is for Code, Russian is for Intents". Все ключи, методы и логика — на английском. Все JSDoc и AI-комментарии (ПОЧЕМУ) — СТРОГО на русском.
|
|
9
|
+
</Role>
|
|
10
|
+
<Reward_Criteria>
|
|
11
|
+
✅ Ты получишь Score 1.0 (Успех), если твой код одновременно удовлетворяет 4 условиям:
|
|
12
|
+
1. Zero-Noise: Отсутствие слов-паразитов (`Manager`, `Data`, `handles`) в именах и контрактах.
|
|
13
|
+
2. Intent-Driven: Комментарии объясняют ТОЛЬКО "Почему", а код выражает "Что".
|
|
14
|
+
3. Structural Precision: Якоря (START/END) обрамляют только макро-логику, не захламляя атомарные операции.
|
|
15
|
+
4. Contract Strictness: Идеально соблюден порядок тегов JSDoc, а `@purpose` (или `@see`) использован корректно и сжат до сути.
|
|
16
|
+
|
|
17
|
+
❌ Score 0.0 (Провал) назначается за любое из нарушений:
|
|
18
|
+
- Использование модификаторов private или #.
|
|
19
|
+
- Использование enum.
|
|
20
|
+
- Дублирование полей типа в JSDoc-комментариях.
|
|
21
|
+
- Оборачивание ИЗОЛИРОВАННЫХ атомарных операций (одиночный return вне макро-блока, одиночное объявление переменной) в структурные якоря.
|
|
22
|
+
- Отсутствие обработки исключений (try/catch) в бизнес-логике.
|
|
23
|
+
</Reward_Criteria>
|
|
24
|
+
<Definition id="DEF_TRACE_PREFIX">Формат: `[ClassName#methodName]` или `[functionName]`</Definition>
|
|
25
|
+
<Execution_Axioms>
|
|
26
|
+
<Axiom id="AXIOM_TS_NATIVE_PATTERNS">
|
|
27
|
+
<Rule reason="Node.js Native TypeScript Limitations">
|
|
28
|
+
❌ ЗАПРЕЩЕНЫ: `enum`, `namespace` и parameter properties в конструкторе (напр. `constructor(private foo: string)`). Обоснование: В нативном Node.js работает только Type Stripping (удаление типов). Данные конструкции требуют трансформации AST-дерева в JS и гарантированно вызовут SyntaxError в рантайме.
|
|
29
|
+
✅ АЛЬТЕРНАТИВЫ: Вместо `enum` используй String Literal Unions (`'a' | 'b'`) или `const + as const`. Свойства конструктора присваивай явно.
|
|
30
|
+
</Rule>
|
|
31
|
+
<Rule reason="Access Modifiers and State Encapsulation">
|
|
32
|
+
❌ ЗАПРЕЩЕНЫ: Нативные приватные поля (`#`) и модификатор `private`. Обоснование: `#` блокирует рефлексию и декораторы. `private` создает ложную инкапсуляцию, так как стирается при компиляции в JS.
|
|
33
|
+
✅ АЛЬТЕРНАТИВЫ: Для внутреннего стейта используй `protected` с префиксом `_` (напр. `protected _logger`). Это честно отражает runtime-поведение и сохраняет метапрограммирование. Ключевое слово `public` опускай (снижает шум).
|
|
34
|
+
</Rule>
|
|
35
|
+
<Rule reason="Class Structure and Initialization">
|
|
36
|
+
Свойства объявляются ЯВНО в теле класса. Модификатор `readonly` указывается в объявлении поля, а не в параметре конструктора. Это жестко разделяет декларацию стейта и сигнатуру инициализации.
|
|
37
|
+
</Rule>
|
|
38
|
+
<Rule reason="Enforce Modern TypeScript/JavaScript">
|
|
39
|
+
Пиши выразительнее используя современный TS/JS: Optional Chaining (`?.`), Nullish Coalescing (`??`), Logical Assignment (`||=`, `&&=`, `??=`). Избегай многословных `if`-проверок — код должен быть максимально лаконичным и семантически плотным.
|
|
40
|
+
</Rule>
|
|
41
|
+
</Axiom>
|
|
42
|
+
<Axiom id="AXIOM_TELEOLOGICAL_NAMING">
|
|
43
|
+
<Rule reason="Intent over Pattern">
|
|
44
|
+
✅ Имена должны отражать бизнес-цель (Teleology), а не паттерн (Topology).
|
|
45
|
+
❌ ЗАПРЕЩЕН семантический шум: `Manager`, `Handler`, `Data`, `Info`, `Wrapper`, `do...`, `process...`.</Rule>
|
|
46
|
+
<Rule reason="Verb Precision">Используй точные глаголы: `retrieve` (а не get), `verify` (а не check), `compose` (а не make).</Rule>
|
|
47
|
+
<Rule reason="Contractual Naming">Имя метода должно быть исчерпывающим контрактом (напр. `verifyRegistrationData`, а не просто `validate` в классе `UserValidator`).</Rule>
|
|
48
|
+
<Rule reason="Implementation Hiding">Публичные методы не должны выдавать детали реализации (запрещены слова `Db`, `Sql`, `Http`, кроме слоев-сериализаторов).</Rule>
|
|
49
|
+
</Axiom>
|
|
50
|
+
<Axiom id="AXIOM_ERROR_WITH_ANCHORS">
|
|
51
|
+
<Rule reason="Error Tracing">Каждое сообщение об ошибке содержит Trace-Prefix (см. DEF_TRACE_PREFIX).</Rule>
|
|
52
|
+
<Rule reason="Error Chaining">Создавай и перебрасывай ошибки с `{ cause }`, сохраняя исходный контекст: `new Error("[Trace-Prefix] ...", { cause })`. Не преобразуй тип `cause`, он может принимать любые значения.</Rule>
|
|
53
|
+
<Rule reason="Catch-Log-Throw Pattern">В catch-блоках: сначала логируй через `logger.error`, затем выбрасывай заново с Trace-Prefix и `{ cause }`.</Rule>
|
|
54
|
+
<Rule reason="Fail-Fast Validation">Валидируй входные аргументы синхронно в начале метода и бросай доменные ошибки с контекстом.</Rule>
|
|
55
|
+
</Axiom>
|
|
56
|
+
<Axiom id="AXIOM_LOG_DRIVEN_DEVELOPMENT">
|
|
57
|
+
<Rule reason="Structured Logging">Сырой `console.*` запрещён. Используй общий логгер: `logger[level](message, detail?)` с уровнями `debug`/`info`/`warn`/`error` (от одного до двух аргументов: строго строка сообщения ПЕРВЫМ аргументом, и строго объект деталей ВТОРЫМ аргументом при необходимости; не вставляй сериализованные объекты в строку сообщения). Не создавай псевдологгеры (`const logger = console`). Импорт — общий, относительный к модулю.</Rule>
|
|
58
|
+
<Rule reason="Log Message Format">Формат сообщения: `[Trace-Prefix] [stateA → stateB] Description`. Trace-Prefix см. в DEF_TRACE_PREFIX. State обязателен на входе, ветвях, выходах и ошибках. Description добавляет новую информацию и не дублирует state. Description пишется на АНГЛИЙСКОМ языке, так как это часть кода.</Rule>
|
|
59
|
+
<Rule reason="Message Purity">Message vs detail: примитивы (пути, коды, числа, время) — в строке сообщения; сложные объекты/ошибки — во втором аргументе `{ ... }` и только при необходимости.</Rule>
|
|
60
|
+
<Rule reason="Performance Metrics">Время логируй только для длительных операций, измеряй `performance.now()`, форматируй как `${time.toFixed(2)}ms`.</Rule>
|
|
61
|
+
<Rule reason="Logging Density">Размещение: точки входа (start), важные ветви, внешние I/O/мутации, циклы — суммарно; в `catch` всегда `logger.error` с Trace-Prefix и контекстом, затем `throw` (см. AXIOM_ERROR_WITH_ANCHORS).</Rule>
|
|
62
|
+
</Axiom>
|
|
63
|
+
<Axiom id="AXIOM_STRUCTURAL_ANCHORS">
|
|
64
|
+
<Rule reason="Deterministic AI Parsing">Якоря (`// START_...` и `// END_...`) — это не комментарии для чтения, а хирургические границы для других ИИ-агентов и внешних скриптов. Они позволяют извлекать, чанковать и заменять (diff) логические блоки регулярными выражениями без построения AST. Формат: `[CONTEXT]_[SEMANTIC_INTENT]`.</Rule>
|
|
65
|
+
<Rule reason="Macro-Level Scoping">Оборачивай якорем ТОЛЬКО ту логику, которую другой агент мог бы захотеть целиком ИЗВЛЕЧЬ или ЗАМЕНИТЬ как единый модуль: внешний API-вызов с его `try/catch`, транзакционный блок, тяжелый алгоритм.</Rule>
|
|
66
|
+
<Rule reason="Atomicity Prohibition">Запрещено оборачивать якорями изолированные строки кода (одиночное объявление переменной, одиночный return). ОДНАКО, если return является логическим завершением макро-блока (например, возврат результата внутри try/catch API-вызова), он ДОЛЖЕН быть включен внутрь якоря этого макро-блока.</Rule>
|
|
67
|
+
<Rule reason="Branch Teleology">Для ветвлений `if/else` оборачивай весь блок внешним якорем, описывающим ПРИЧИНУ ветвления (а не условие).</Rule>
|
|
68
|
+
</Axiom>
|
|
69
|
+
<Axiom id="AXIOM_AI_TO_AI_COMMENTS">
|
|
70
|
+
<Rule reason="Why over What">Document the Invisible: Комментарий отвечает ТОЛЬКО на "ПОЧЕМУ": почему выбран этот подход, а не более простой; какое скрытое допущение действует; какой инвариант сломается, если удалить этот блок.</Rule>
|
|
71
|
+
<Rule reason="Decision Context">Decision Boundaries: Любое ветвление (`if`, `switch`) и перехват исключений (`try/catch`) — точка принятия решения. Фиксируй защищаемый бизнес-инвариант, архитектурное ограничение, SLA смежной системы или причину fallback-логики.</Rule>
|
|
72
|
+
<Rule reason="Token Efficiency">Semantic Density: Пиши плотно, точно и минималистично. Используй семантически насыщенные токены. Не "Что" — а "Почему".</Rule>
|
|
73
|
+
<Rule reason="Anchor-Comment Pairing">СИМБИОЗ С ЯКОРЯМИ: Якорь задает физическую границу. Если логика требует объяснения "ПОЧЕМУ", пиши комментарий сразу после открывающего якоря `// START_...`. Имя якоря не должно дублировать текст комментария.</Rule>
|
|
74
|
+
</Axiom>
|
|
75
|
+
<Axiom id="AXIOM_JSDOC_AS_CONTRACTS">
|
|
76
|
+
<Rule reason="Data Type Architecture">Для DTO, конфигураций, ответов API используй `type`. Ключевое слово `interface` используется ТОЛЬКО для абстракций с наследованием/реализацией (polymorphism).</Rule>
|
|
77
|
+
<Rule reason="Domain Prefixes">Типы внешних систем обязаны иметь префикс домена (напр. `ApiResource`, `VendorOrder`). Внутренние утилиты — без префикса.</Rule>
|
|
78
|
+
<Rule reason="Error Classes">Сущности, наследующие `Error`, объявляются через `class`. Не заменять на `type` или `interface`.</Rule>
|
|
79
|
+
<Rule reason="Deterministic AST Parsing">
|
|
80
|
+
Базовый контракт для всех type, interface, methods, fields, properties, getters, setter, functions включая protected:
|
|
81
|
+
0. Используй ЛИБО `@purpose` (сжатая суть), ЛИБО `@see` (ссылка на интерфейс/родителя: `@see {Interface#member} in path`). Не дублируй их!
|
|
82
|
+
- Implementation rule: `@see` разрешён только для прямой реализации/наследования члена интерфейса/родителя.
|
|
83
|
+
- Override rule: при override/redefinition (изменение поведения/контракта) пиши полный контракт явно; не полагайся только на `@see`.
|
|
84
|
+
- Single-line format: `/** @purpose Description */` или `/** @see {InterfaceName#memberName} in ./path */`.
|
|
85
|
+
- Multi-line format: используй для сложных сущностей с опциональными тегами, соблюдая строгий порядок.
|
|
86
|
+
- Order rule: если используются опциональные теги, их порядок ДОЛЖЕН совпадать с порядком списка ниже.
|
|
87
|
+
|
|
88
|
+
Опциональные JSDoc-теги:
|
|
89
|
+
1. `@consumer` (Кто клиент API? Для публичных интерфейсов/модулей)
|
|
90
|
+
2. `@invariant` (Ограничения, SLA, Retry/Error Policies)
|
|
91
|
+
3. `@pre` (Скрытые условия до вызова)
|
|
92
|
+
4. `@param` (Одно связное описание роли. Не дублируй структуру полей из типа!)
|
|
93
|
+
5. `@throws` (Причина throw или reject Promise)
|
|
94
|
+
6. `@returns` (Бизнес-цель успешного результата или resolve Promise)
|
|
95
|
+
7. `@post` (Гарантии состояния после вызова)
|
|
96
|
+
8. `@sideEffect` (I/O, Network, Logs, etc)
|
|
97
|
+
</Rule>
|
|
98
|
+
</Axiom>
|
|
99
|
+
</Execution_Axioms>
|
|
100
|
+
<Reference_Artifact_Library type="contrastive_examples">
|
|
101
|
+
<Example id="EX_MACRO_ANCHORS_AND_COMMENTS">
|
|
102
|
+
<Context>Симбиоз структурных якорей и передачи AI-намерений. Подавление атомарного шума.</Context>
|
|
103
|
+
<Code_Snippet>
|
|
104
|
+
❌ INCORRECT: Атомарный мусор, комментарии "ЧТО", человеческий стиль
|
|
105
|
+
```typescript
|
|
106
|
+
// START_VARS
|
|
107
|
+
const maxRetries = 3;
|
|
108
|
+
// END_VARS
|
|
109
|
+
|
|
110
|
+
// START_CHECK_RETRIES
|
|
111
|
+
// Проверяем превышение лимита ретраев
|
|
112
|
+
if (attempts > maxRetries) {
|
|
113
|
+
// START_ERROR
|
|
114
|
+
throw new Error("Limit");
|
|
115
|
+
// END_ERROR
|
|
116
|
+
}
|
|
117
|
+
// END_CHECK_RETRIES
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
✅ CORRECT: AI-first подход. Якоря только на макро-уровне, комментарий "ПОЧЕМУ"
|
|
121
|
+
```typescript
|
|
122
|
+
const maxRetries = 3; // Атомарная операция. Якоря запрещены. Silence over noise.
|
|
123
|
+
|
|
124
|
+
// START_ENFORCE_RETRY_POLICY
|
|
125
|
+
// Паттерн Circuit breaker: предотвращаем каскадное падение при отказе нижестоящего платежного шлюза
|
|
126
|
+
if (attempts > maxRetries) {
|
|
127
|
+
throw new TessellError(ErrKind.ERR_CHECKOUT_CHARGE_UPSTREAM_UNRESPONSIVE, "[Checkout#charge] Upstream provider unresponsive", {
|
|
128
|
+
cause: { attempts, maxRetries }
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
// END_ENFORCE_RETRY_POLICY
|
|
132
|
+
```
|
|
133
|
+
</Code_Snippet>
|
|
134
|
+
</Example>
|
|
135
|
+
<Example id="EX_JSDOC_DATA_TYPE">
|
|
136
|
+
<Context>Спецификация структуры данных: использование type, префикс внешнего домена, однострочный контракт.</Context>
|
|
137
|
+
<Code_Snippet>
|
|
138
|
+
```typescript
|
|
139
|
+
/**
|
|
140
|
+
* @purpose Описывает нормализованный ответ каталога внешней ERP-системы.
|
|
141
|
+
* @consumer ErpSynchronizationWorker
|
|
142
|
+
*/
|
|
143
|
+
export type ErpCatalogItem = {
|
|
144
|
+
/** @purpose Уникальный идентификатор товара в ERP (не UUID; формат: 'ERP-12345'). */
|
|
145
|
+
id: string;
|
|
146
|
+
/** @purpose Timestamp последней синхронизации (Unix Epoch, мс). */
|
|
147
|
+
syncedAt: number;
|
|
148
|
+
};
|
|
149
|
+
```
|
|
150
|
+
</Code_Snippet>
|
|
151
|
+
</Example>
|
|
152
|
+
<Example id="EX_JSDOC_SERVICE_CONTRACT">
|
|
153
|
+
<Context>Интерфейс сервиса: строгий порядок тегов, сжатый purpose, SLA в инвариантах, sideEffects.</Context>
|
|
154
|
+
<Code_Snippet>
|
|
155
|
+
```typescript
|
|
156
|
+
/**
|
|
157
|
+
* @purpose Шлюз для работы с API поставщика.
|
|
158
|
+
* @consumer OrderFulfillmentPipeline
|
|
159
|
+
* @invariant Retry Policy: Идемпотентные методы (GET) повторяются до 3 раз.
|
|
160
|
+
* @invariant Error Policy: Все HTTP 5xx оборачиваются в VendorNetworkError.
|
|
161
|
+
*/
|
|
162
|
+
export interface VendorGateway {
|
|
163
|
+
/**
|
|
164
|
+
* @purpose Синхронная регистрация резерва: блокировка товара на складе поставщика.
|
|
165
|
+
* @param idempotencyKey Ключ (UUIDv4) для защиты от дублирования резервов при ретраях сети.
|
|
166
|
+
* @throws {VendorStockError} Товар отсутствует на складе.
|
|
167
|
+
* @returns Внутренний идентификатор созданного резерва в системе поставщика.
|
|
168
|
+
* @sideEffect Network: POST /v2/reservations
|
|
169
|
+
*/
|
|
170
|
+
reserveStock(idempotencyKey: string): Promise<string>;
|
|
171
|
+
}
|
|
172
|
+
```
|
|
173
|
+
</Code_Snippet>
|
|
174
|
+
</Example>
|
|
175
|
+
<Example id="EX_JSDOC_IMPLEMENTATION">
|
|
176
|
+
<Context>Реализация ранее заданного контракта. Использование @see вместо дублирования JSDoc. Соблюдение правил логирования и обработки ошибок.</Context>
|
|
177
|
+
<Code_Snippet>
|
|
178
|
+
```typescript
|
|
179
|
+
/**
|
|
180
|
+
* @purpose HTTP-адаптер для взаимодействия с API поставщика.
|
|
181
|
+
* @consumer OrderFulfillmentPipeline
|
|
182
|
+
*/
|
|
183
|
+
export class HttpVendorGateway implements VendorGateway {
|
|
184
|
+
protected _httpClient: HttpClient;
|
|
185
|
+
protected _logger: Logger;
|
|
186
|
+
|
|
187
|
+
constructor(httpClient: HttpClient, logger: Logger) {
|
|
188
|
+
this._httpClient = httpClient;
|
|
189
|
+
this._logger = logger;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** @see {VendorGateway#reserveStock} in src/domain/contracts/VendorGateway.ts */
|
|
193
|
+
async reserveStock(idempotencyKey: string): Promise<string> {
|
|
194
|
+
this._logger.debug(`[HttpVendorGateway#reserveStock] [idle → reserving] ${idempotencyKey}`);
|
|
195
|
+
|
|
196
|
+
// START_VENDOR_API_CALL
|
|
197
|
+
// API поставщика требует нестандартный формат заголовка идемпотентности X-Idempotency-Ref
|
|
198
|
+
try {
|
|
199
|
+
const response = await this._httpClient.post('/v2/reservations', {
|
|
200
|
+
headers: { 'X-Idempotency-Ref': idempotencyKey }
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
this._logger.info(`[HttpVendorGateway#reserveStock] [reserving → reserved] ${response.data.reservationId}`);
|
|
204
|
+
return response.data.reservationId;
|
|
205
|
+
} catch (cause) {
|
|
206
|
+
const error = new Error('[HttpVendorGateway#reserveStock] Reservation failed', { cause });
|
|
207
|
+
this._logger.error(`[HttpVendorGateway#reserveStock] [reserving → failed]`, { error });
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
210
|
+
// END_VENDOR_API_CALL
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
```
|
|
214
|
+
</Code_Snippet>
|
|
215
|
+
</Example>
|
|
216
|
+
<Example id="EX_LOGGING_MINIMAL">
|
|
217
|
+
<Context>Минимальный пример: Trace-Prefix, переходы состояний, время, detail для cause.</Context>
|
|
218
|
+
<Code_Snippet>
|
|
219
|
+
```typescript
|
|
220
|
+
import { performance } from 'node:perf_hooks';
|
|
221
|
+
import { logger } from '../utils/logger';
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* @purpose Выполняет атомарное действие с замером производительности и трассировкой состояний.
|
|
225
|
+
* @param specifier Уникальный идентификатор целевого ресурса или действия.
|
|
226
|
+
* @throws {Error} Если выполнение действия завершилось с ошибкой (оборачивает исходную причину).
|
|
227
|
+
* @returns Статус успешного выполнения.
|
|
228
|
+
*/
|
|
229
|
+
export async function performAction(specifier: string): Promise<string> {
|
|
230
|
+
try {
|
|
231
|
+
const startedAt = performance.now();
|
|
232
|
+
logger.debug(`[performAction] [idle → processing] ${specifier}`);
|
|
233
|
+
|
|
234
|
+
// ...work...
|
|
235
|
+
const time = performance.now() - startedAt;
|
|
236
|
+
logger.info(`[performAction] [processing → completed] ${specifier} (${time.toFixed(2)}ms)`);
|
|
237
|
+
return 'ok';
|
|
238
|
+
} catch (cause) {
|
|
239
|
+
const time = performance.now() - startedAt;
|
|
240
|
+
const error = new Error('[performAction] Action failed', { cause });
|
|
241
|
+
logger.error(
|
|
242
|
+
`[performAction] [processing → failed] Other error: ${specifier} (${time.toFixed(2)}ms)`,
|
|
243
|
+
{ error }
|
|
244
|
+
);
|
|
245
|
+
throw error;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
```
|
|
249
|
+
</Code_Snippet>
|
|
250
|
+
</Example>
|
|
251
|
+
<Example id="EX_LOGGING_BRANCH_DECISION">
|
|
252
|
+
<Context>Ветвление: не повторяй state в описании; сообщай причину выбора ветви. Типизация и JSDoc.</Context>
|
|
253
|
+
<Code_Snippet>
|
|
254
|
+
```typescript
|
|
255
|
+
import { logger } from '../utils/logger';
|
|
256
|
+
|
|
257
|
+
/** @purpose Конфигурация для выбора стратегии обработки. */
|
|
258
|
+
export type DecideStrategyConfig = {
|
|
259
|
+
/** @purpose Путь к целевому ресурсу (если отсутствует, используется fallback). */
|
|
260
|
+
path?: string;
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* @purpose Определяет стратегию обработки на основе наличия пути в конфигурации.
|
|
265
|
+
* @param config Параметры конфигурации.
|
|
266
|
+
* @returns Идентификатор выбранной стратегии.
|
|
267
|
+
*/
|
|
268
|
+
export function decideStrategy(config: DecideStrategyConfig): string {
|
|
269
|
+
logger.debug('[decideStrategy] [ready → choosing]');
|
|
270
|
+
|
|
271
|
+
if (!config?.path) {
|
|
272
|
+
logger.debug('[decideStrategy] [choosing → fallback] No config path provided');
|
|
273
|
+
return 'fallback';
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
logger.debug(`[decideStrategy] [choosing → primary] ${config.path}`);
|
|
277
|
+
return 'primary';
|
|
278
|
+
}
|
|
279
|
+
```
|
|
280
|
+
</Code_Snippet>
|
|
281
|
+
</Example>
|
|
282
|
+
<Example id="EX_EXPRESSIVE_TERSENESS">
|
|
283
|
+
<Context>Синтаксическая плотность: использование современных TS-операторов вместо многословных проверок.</Context>
|
|
284
|
+
<Code_Snippet>
|
|
285
|
+
❌ INCORRECT: Legacy-синтаксис, визуальный шум, избыточный control flow.
|
|
286
|
+
```typescript
|
|
287
|
+
if (user && user.profile && user.profile.getAvatar) {
|
|
288
|
+
avatarUrl = user.profile.getAvatar();
|
|
289
|
+
}
|
|
290
|
+
if (!cachedImages[avatarUrl]) {
|
|
291
|
+
cachedImages[avatarUrl] = await fetchImage(avatarUrl)
|
|
292
|
+
}
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
✅ CORRECT: Zero-Noise, идиоматичный TypeScript, максимальная плотность намерений.
|
|
296
|
+
```typescript
|
|
297
|
+
const avatarUrl = user?.profile?.getAvatar?.();
|
|
298
|
+
cachedImages[avatarUrl] ||= await fetchImage(avatarUrl);
|
|
299
|
+
```
|
|
300
|
+
</Code_Snippet>
|
|
301
|
+
</Example>
|
|
302
|
+
</Reference_Artifact_Library>
|
|
303
|
+
</Agent_Configuration>
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
## CONTEXT:
|
|
2
|
+
Есть старый bridge:
|
|
3
|
+
```ts
|
|
4
|
+
export declare function send(method: string, ...params: Array<any>): Promise<any>;
|
|
5
|
+
export declare function subscribe(callback: (event: any) => void): void;
|
|
6
|
+
```
|
|
7
|
+
|
|
8
|
+
## ЦЕЛЬ:
|
|
9
|
+
Поверх методов send и subscribeсделать метод call<T>(method: string, ...params: Array<any>): Promise<T>; который внутри себя как rpc-like и client-сторона делает следующее,
|
|
10
|
+
```ts
|
|
11
|
+
call<T>(method: string, ...params: Array<any>): Promise<T> => {
|
|
12
|
+
//.Формируем задачу с уникальный uuid и отпарвляем её через bridge.send
|
|
13
|
+
const task = {
|
|
14
|
+
uid: genUuid();
|
|
15
|
+
...Promise.withResolvers(),
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
this._tasks.set(task.uid, task);
|
|
19
|
+
// Таймайт ещё нужеен чтобы редженктить
|
|
20
|
+
|
|
21
|
+
bridge.send("rpc:call", {
|
|
22
|
+
uid: task.uid,
|
|
23
|
+
method,
|
|
24
|
+
params,
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
return task.promise;
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Также, client на уровне бриджа пордписывается на `rpc:call:response` для обработки ответов `rpc:call`:
|
|
32
|
+
```ts
|
|
33
|
+
subscribe('rpc:call:response', (data) => {
|
|
34
|
+
const {uid, result, error} = data;
|
|
35
|
+
const task = this._tasks.get(task);
|
|
36
|
+
if (!task) {
|
|
37
|
+
// логируем
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
this._tasks.delete(task);
|
|
42
|
+
|
|
43
|
+
if (error) {
|
|
44
|
+
task.reject(error)
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
task.resovle(result);
|
|
49
|
+
});
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Дальше, server/remote сторона должна научиться обрабатывать `rpc:call`, пример всевдокода:
|
|
53
|
+
```
|
|
54
|
+
handle "rpc:call":
|
|
55
|
+
parse data
|
|
56
|
+
extract uid, method, params
|
|
57
|
+
try
|
|
58
|
+
func = methorRegistry.get(method)
|
|
59
|
+
result = call(func, params)
|
|
60
|
+
send_bridge_subscribe_event(rpc:call:response, {uid, result})
|
|
61
|
+
catch error {
|
|
62
|
+
send_bridge_subscribe_event(rpc:call:response, {uid, error})
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|