@autobe/agent 0.9.0 → 0.9.2

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 (62) hide show
  1. package/lib/AutoBeAgent.js +7 -1
  2. package/lib/AutoBeAgent.js.map +1 -1
  3. package/lib/constants/AutoBeSystemPromptConstant.d.ts +5 -3
  4. package/lib/constants/AutoBeSystemPromptConstant.js.map +1 -1
  5. package/lib/context/IAutoBeApplicationProps.d.ts +0 -61
  6. package/lib/factory/createAutoBeApplication.js +15 -135
  7. package/lib/factory/createAutoBeApplication.js.map +1 -1
  8. package/lib/index.mjs +1054 -1037
  9. package/lib/index.mjs.map +1 -1
  10. package/lib/orchestrate/analyze/orchestrateAnalyze.js +4 -30
  11. package/lib/orchestrate/analyze/orchestrateAnalyze.js.map +1 -1
  12. package/lib/orchestrate/interface/orchestrateInterface.js +9 -3
  13. package/lib/orchestrate/interface/orchestrateInterface.js.map +1 -1
  14. package/lib/orchestrate/test/compileTestScenario.d.ts +5 -0
  15. package/lib/orchestrate/test/compileTestScenario.js +57 -0
  16. package/lib/orchestrate/test/compileTestScenario.js.map +1 -0
  17. package/lib/orchestrate/test/filterTestFileName.d.ts +1 -0
  18. package/lib/orchestrate/test/filterTestFileName.js +13 -0
  19. package/lib/orchestrate/test/filterTestFileName.js.map +1 -0
  20. package/lib/orchestrate/test/orchestrateTest.js +6 -3
  21. package/lib/orchestrate/test/orchestrateTest.js.map +1 -1
  22. package/lib/orchestrate/test/orchestrateTestCorrect.d.ts +2 -2
  23. package/lib/orchestrate/test/orchestrateTestCorrect.js +172 -87
  24. package/lib/orchestrate/test/orchestrateTestCorrect.js.map +1 -1
  25. package/lib/orchestrate/test/orchestrateTestScenario.js +98 -83
  26. package/lib/orchestrate/test/orchestrateTestScenario.js.map +1 -1
  27. package/lib/orchestrate/test/orchestrateTestWrite.d.ts +4 -0
  28. package/lib/orchestrate/test/{orchestrateTestProgress.js → orchestrateTestWrite.js} +27 -54
  29. package/lib/orchestrate/test/orchestrateTestWrite.js.map +1 -0
  30. package/lib/orchestrate/test/structures/IAutoBeTestScenarioApplication.d.ts +18 -20
  31. package/lib/orchestrate/test/structures/IAutoBeTestScenarioArtifacts.d.ts +7 -0
  32. package/lib/orchestrate/test/structures/IAutoBeTestScenarioArtifacts.js +3 -0
  33. package/lib/orchestrate/test/structures/IAutoBeTestScenarioArtifacts.js.map +1 -0
  34. package/lib/orchestrate/test/transformTestCorrectHistories.d.ts +2 -2
  35. package/lib/orchestrate/test/transformTestCorrectHistories.js +38 -16
  36. package/lib/orchestrate/test/transformTestCorrectHistories.js.map +1 -1
  37. package/lib/orchestrate/test/transformTestWriteHistories.d.ts +7 -0
  38. package/lib/orchestrate/test/transformTestWriteHistories.js +59 -0
  39. package/lib/orchestrate/test/transformTestWriteHistories.js.map +1 -0
  40. package/lib/structures/IAutoBeProps.d.ts +12 -1
  41. package/package.json +4 -5
  42. package/src/AutoBeAgent.ts +14 -2
  43. package/src/constants/AutoBeSystemPromptConstant.ts +5 -3
  44. package/src/context/IAutoBeApplicationProps.ts +0 -62
  45. package/src/orchestrate/analyze/orchestrateAnalyze.ts +4 -34
  46. package/src/orchestrate/interface/orchestrateInterface.ts +7 -0
  47. package/src/orchestrate/test/compileTestScenario.ts +64 -0
  48. package/src/orchestrate/test/filterTestFileName.ts +9 -0
  49. package/src/orchestrate/test/orchestrateTest.ts +15 -9
  50. package/src/orchestrate/test/orchestrateTestCorrect.ts +288 -128
  51. package/src/orchestrate/test/orchestrateTestScenario.ts +23 -6
  52. package/src/orchestrate/test/{orchestrateTestProgress.ts → orchestrateTestWrite.ts} +56 -87
  53. package/src/orchestrate/test/structures/IAutoBeTestScenarioApplication.ts +18 -20
  54. package/src/orchestrate/test/structures/IAutoBeTestScenarioArtifacts.ts +8 -0
  55. package/src/orchestrate/test/transformTestCorrectHistories.ts +41 -17
  56. package/src/orchestrate/test/{transformTestProgressHistories.ts → transformTestWriteHistories.ts} +21 -10
  57. package/src/structures/IAutoBeProps.ts +17 -1
  58. package/lib/orchestrate/test/orchestrateTestProgress.d.ts +0 -5
  59. package/lib/orchestrate/test/orchestrateTestProgress.js.map +0 -1
  60. package/lib/orchestrate/test/transformTestProgressHistories.d.ts +0 -8
  61. package/lib/orchestrate/test/transformTestProgressHistories.js +0 -47
  62. package/lib/orchestrate/test/transformTestProgressHistories.js.map +0 -1
@@ -45,16 +45,15 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
45
45
  return (mod && mod.__esModule) ? mod : { "default": mod };
46
46
  };
47
47
  Object.defineProperty(exports, "__esModule", { value: true });
48
- exports.orchestrateTestProgress = orchestrateTestProgress;
49
- exports.filterDocument = filterDocument;
48
+ exports.orchestrateTestWrite = orchestrateTestWrite;
50
49
  const __typia_transform__validateReport = __importStar(require("typia/lib/internal/_validateReport.js"));
51
50
  const core_1 = require("@agentica/core");
52
- const openapi_1 = require("@samchon/openapi");
53
51
  const typia_1 = __importDefault(require("typia"));
54
52
  const assertSchemaModel_1 = require("../../context/assertSchemaModel");
55
53
  const enforceToolCall_1 = require("../../utils/enforceToolCall");
56
- const transformTestProgressHistories_1 = require("./transformTestProgressHistories");
57
- function orchestrateTestProgress(ctx, scenarios) {
54
+ const compileTestScenario_1 = require("./compileTestScenario");
55
+ const transformTestWriteHistories_1 = require("./transformTestWriteHistories");
56
+ function orchestrateTestWrite(ctx, scenarios) {
58
57
  return __awaiter(this, void 0, void 0, function* () {
59
58
  const start = new Date();
60
59
  let complete = 0;
@@ -70,7 +69,7 @@ function orchestrateTestProgress(ctx, scenarios) {
70
69
  const event = {
71
70
  type: "testWrite",
72
71
  created_at: start.toISOString(),
73
- filename: `${code.domain}/${scenario.functionName}.ts`,
72
+ filename: `test/features/api/${code.domain}/${scenario.functionName}.ts`,
74
73
  content: code.content,
75
74
  completed: ++complete,
76
75
  total: scenarios.length,
@@ -98,18 +97,14 @@ function process(ctx, scenario) {
98
97
  const pointer = {
99
98
  value: null,
100
99
  };
101
- const document = filterDocument(scenario, ctx.state().interface.document);
102
- const files = Object.entries(yield ctx.compiler.interface.compile(document));
103
- const filter = (prefix) => Object.fromEntries(files.filter(([key]) => key.startsWith(prefix)));
100
+ const artifacts = yield (0, compileTestScenario_1.compileTestScenario)(ctx, scenario);
104
101
  const agentica = new core_1.MicroAgentica({
105
102
  model: ctx.model,
106
103
  vendor: ctx.vendor,
107
104
  config: Object.assign({}, ((_a = ctx.config) !== null && _a !== void 0 ? _a : {})),
108
- histories: (0, transformTestProgressHistories_1.transformTestProgressHistories)({
109
- scenario: scenario,
110
- dto: filter("src/api/structures"),
111
- sdk: filter("src/api/functional"),
112
- e2e: filter("test/features"),
105
+ histories: (0, transformTestWriteHistories_1.transformTestWriteHistories)({
106
+ scenario,
107
+ artifacts,
113
108
  }),
114
109
  controllers: [
115
110
  createApplication({
@@ -125,45 +120,23 @@ function process(ctx, scenario) {
125
120
  yield agentica.conversate("Create e2e test functions.");
126
121
  if (pointer.value === null)
127
122
  throw new Error("Failed to create test code.");
123
+ const typeReferences = Array.from(new Set(Object.keys(artifacts.document.components.schemas).map((key) => key.split(".")[0])));
124
+ pointer.value.content = pointer.value.content
125
+ .replace(/^[ \t]*import\b[\s\S]*?;[ \t]*$/gm, "")
126
+ .trim();
127
+ pointer.value.content = [
128
+ `import { TestValidator } from "@nestia/e2e";`,
129
+ `import typia, { tags } from "typia";`,
130
+ "",
131
+ `import api from "@ORGANIZATION/PROJECT-api";`,
132
+ ...typeReferences.map((ref) => `import type { ${ref} } from "@ORGANIZATION/PROJECT-api/lib/structures/${ref}";`),
133
+ "",
134
+ pointer.value.content,
135
+ ].join("\n");
136
+ pointer.value.content = pointer.value.content.replaceAll('string & Format<"uuid">', 'string & tags.Format<"uuid">');
128
137
  return pointer.value;
129
138
  });
130
139
  }
131
- function filterDocument(scenario, document) {
132
- const operations = document.operations.filter((op) => {
133
- if (scenario.endpoint.method === op.method &&
134
- scenario.endpoint.path === op.path) {
135
- return true;
136
- }
137
- else if (scenario.dependencies.some((dp) => dp.endpoint.method === op.method && dp.endpoint.path === op.path)) {
138
- return true;
139
- }
140
- });
141
- const components = {
142
- schemas: {},
143
- };
144
- const visit = (typeName) => {
145
- openapi_1.OpenApiTypeChecker.visit({
146
- components: document.components,
147
- schema: { $ref: `#/components/schemas/${typeName}` },
148
- closure: (s) => {
149
- if (openapi_1.OpenApiTypeChecker.isReference(s)) {
150
- const key = s.$ref.split("/").pop();
151
- components.schemas[key] = document.components.schemas[key];
152
- }
153
- },
154
- });
155
- };
156
- for (const op of operations) {
157
- if (op.requestBody)
158
- visit(op.requestBody.typeName);
159
- if (op.responseBody)
160
- visit(op.responseBody.typeName);
161
- }
162
- return {
163
- operations,
164
- components,
165
- };
166
- }
167
140
  function createApplication(props) {
168
141
  (0, assertSchemaModel_1.assertSchemaModel)(props.model);
169
142
  const application = collection[props.model];
@@ -193,7 +166,7 @@ const claude = {
193
166
  properties: {
194
167
  scenario: {
195
168
  title: "Strategic approach for test implementation",
196
- description: "Strategic approach for test implementation.\n\nDefine the high-level strategy and logical flow for testing the given\nscenario. Focus on test methodology, data preparation, and assertion\nstrategy.\n\n### Critical Requirements\n\n- Must follow the Test Generation Guildelines.\n- Must Planning the test code Never occur the typescript compile error.\n\n### Planning Elements:\n\n#### Test Methodology\n\n- Identify test scenario type (CRUD operation, authentication flow,\n validation test)\n- Define test data requirements and preparation strategy\n- Plan positive/negative test cases and edge cases\n- Design assertion logic and validation points\n\n#### Execution Strategy\n\n- Outline step-by-step test execution flow\n- Plan error handling and exception plans\n- Define cleanup and teardown procedures\n- Identify dependencies and prerequisites\n\n### Example Plan:\n\n Test Strategy: Article Creation Validation\n 1. Prepare valid article data with required fields\n 2. Execute POST request to create article\n 3. Validate response structure and data integrity\n 4. Test error plans (missing fields, invalid data)\n 5. Verify database state changes\n 6. Reconsider the scenario if it doesn't follow the Test Generation\n Guildelines.",
169
+ description: "Strategic approach for test implementation.\n\nDefine the high-level strategy and logical flow for testing the given\nscenario. Focus on test methodology, data preparation, and assertion\nstrategy.\n\n### Critical Requirements\n\n- Must follow the Test Generation Guidelines.\n- Must Planning the test code Never occur the TypeScript compile error.\n- NEVER include import statements in planning or implementation.\n\n### Planning Elements:\n\n#### Test Methodology\n\n- Identify test scenario type (CRUD operation, authentication flow,\n validation test)\n- Define test data requirements and preparation strategy\n- Plan positive/negative test cases and edge cases\n- Design assertion logic and validation points\n\n#### Execution Strategy\n\n- Outline step-by-step test execution flow\n- Plan error handling and exception plans\n- Define cleanup and teardown procedures\n- Identify dependencies and prerequisites\n\n### Example Plan:\n\n Test Strategy: Article Creation Validation\n 1. Prepare valid article data with required fields\n 2. Execute POST request to create article\n 3. Validate response structure and data integrity\n 4. Test error plans (missing fields, invalid data)\n 5. Verify database state changes\n 6. Reconsider the scenario if it doesn't follow the Test Generation\n Guidelines.",
197
170
  type: "string"
198
171
  },
199
172
  domain: {
@@ -275,7 +248,7 @@ const collection = {
275
248
  properties: {
276
249
  scenario: {
277
250
  title: "Strategic approach for test implementation",
278
- description: "Strategic approach for test implementation.\n\nDefine the high-level strategy and logical flow for testing the given\nscenario. Focus on test methodology, data preparation, and assertion\nstrategy.\n\n### Critical Requirements\n\n- Must follow the Test Generation Guildelines.\n- Must Planning the test code Never occur the typescript compile error.\n\n### Planning Elements:\n\n#### Test Methodology\n\n- Identify test scenario type (CRUD operation, authentication flow,\n validation test)\n- Define test data requirements and preparation strategy\n- Plan positive/negative test cases and edge cases\n- Design assertion logic and validation points\n\n#### Execution Strategy\n\n- Outline step-by-step test execution flow\n- Plan error handling and exception plans\n- Define cleanup and teardown procedures\n- Identify dependencies and prerequisites\n\n### Example Plan:\n\n Test Strategy: Article Creation Validation\n 1. Prepare valid article data with required fields\n 2. Execute POST request to create article\n 3. Validate response structure and data integrity\n 4. Test error plans (missing fields, invalid data)\n 5. Verify database state changes\n 6. Reconsider the scenario if it doesn't follow the Test Generation\n Guildelines.",
251
+ description: "Strategic approach for test implementation.\n\nDefine the high-level strategy and logical flow for testing the given\nscenario. Focus on test methodology, data preparation, and assertion\nstrategy.\n\n### Critical Requirements\n\n- Must follow the Test Generation Guidelines.\n- Must Planning the test code Never occur the TypeScript compile error.\n- NEVER include import statements in planning or implementation.\n\n### Planning Elements:\n\n#### Test Methodology\n\n- Identify test scenario type (CRUD operation, authentication flow,\n validation test)\n- Define test data requirements and preparation strategy\n- Plan positive/negative test cases and edge cases\n- Design assertion logic and validation points\n\n#### Execution Strategy\n\n- Outline step-by-step test execution flow\n- Plan error handling and exception plans\n- Define cleanup and teardown procedures\n- Identify dependencies and prerequisites\n\n### Example Plan:\n\n Test Strategy: Article Creation Validation\n 1. Prepare valid article data with required fields\n 2. Execute POST request to create article\n 3. Validate response structure and data integrity\n 4. Test error plans (missing fields, invalid data)\n 5. Verify database state changes\n 6. Reconsider the scenario if it doesn't follow the Test Generation\n Guidelines.",
279
252
  type: "string"
280
253
  },
281
254
  domain: {
@@ -360,7 +333,7 @@ const collection = {
360
333
  scenario: {
361
334
  type: "string",
362
335
  title: "Strategic approach for test implementation",
363
- description: "Strategic approach for test implementation.\n\nDefine the high-level strategy and logical flow for testing the given\nscenario. Focus on test methodology, data preparation, and assertion\nstrategy.\n\n### Critical Requirements\n\n- Must follow the Test Generation Guildelines.\n- Must Planning the test code Never occur the typescript compile error.\n\n### Planning Elements:\n\n#### Test Methodology\n\n- Identify test scenario type (CRUD operation, authentication flow,\n validation test)\n- Define test data requirements and preparation strategy\n- Plan positive/negative test cases and edge cases\n- Design assertion logic and validation points\n\n#### Execution Strategy\n\n- Outline step-by-step test execution flow\n- Plan error handling and exception plans\n- Define cleanup and teardown procedures\n- Identify dependencies and prerequisites\n\n### Example Plan:\n\n Test Strategy: Article Creation Validation\n 1. Prepare valid article data with required fields\n 2. Execute POST request to create article\n 3. Validate response structure and data integrity\n 4. Test error plans (missing fields, invalid data)\n 5. Verify database state changes\n 6. Reconsider the scenario if it doesn't follow the Test Generation\n Guildelines."
336
+ description: "Strategic approach for test implementation.\n\nDefine the high-level strategy and logical flow for testing the given\nscenario. Focus on test methodology, data preparation, and assertion\nstrategy.\n\n### Critical Requirements\n\n- Must follow the Test Generation Guidelines.\n- Must Planning the test code Never occur the TypeScript compile error.\n- NEVER include import statements in planning or implementation.\n\n### Planning Elements:\n\n#### Test Methodology\n\n- Identify test scenario type (CRUD operation, authentication flow,\n validation test)\n- Define test data requirements and preparation strategy\n- Plan positive/negative test cases and edge cases\n- Design assertion logic and validation points\n\n#### Execution Strategy\n\n- Outline step-by-step test execution flow\n- Plan error handling and exception plans\n- Define cleanup and teardown procedures\n- Identify dependencies and prerequisites\n\n### Example Plan:\n\n Test Strategy: Article Creation Validation\n 1. Prepare valid article data with required fields\n 2. Execute POST request to create article\n 3. Validate response structure and data integrity\n 4. Test error plans (missing fields, invalid data)\n 5. Verify database state changes\n 6. Reconsider the scenario if it doesn't follow the Test Generation\n Guidelines."
364
337
  },
365
338
  domain: {
366
339
  type: "string",
@@ -425,4 +398,4 @@ const collection = {
425
398
  ]
426
399
  },
427
400
  };
428
- //# sourceMappingURL=orchestrateTestProgress.js.map
401
+ //# sourceMappingURL=orchestrateTestWrite.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orchestrateTestWrite.js","sourceRoot":"","sources":["../../../src/orchestrate/test/orchestrateTestWrite.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,oDA8BC;;AA3CD,yCAAoE;AAIpE,kDAA0B;AAG1B,uEAAoE;AACpE,iEAA8D;AAC9D,+DAA4D;AAE5D,+EAA4E;AAE5E,SAAsB,oBAAoB,CACxC,GAAyB,EACzB,SAA+B;;QAE/B,MAAM,KAAK,GAAS,IAAI,IAAI,EAAE,CAAC;QAC/B,IAAI,QAAQ,GAAW,CAAC,CAAC;QAEzB,MAAM,MAAM,GAA2B,MAAM,OAAO,CAAC,GAAG;QACtD;;;;WAIG;QACH,SAAS,CAAC,GAAG,CAAC,CAAO,QAAQ,EAAE,EAAE;;YAC/B,MAAM,IAAI,GAAyB,MAAM,OAAO,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;YAChE,MAAM,KAAK,GAAyB;gBAClC,IAAI,EAAE,WAAW;gBACjB,UAAU,EAAE,KAAK,CAAC,WAAW,EAAE;gBAC/B,QAAQ,EAAE,qBAAqB,IAAI,CAAC,MAAM,IAAI,QAAQ,CAAC,YAAY,KAAK;gBACxE,OAAO,EAAE,IAAI,CAAC,OAAO;gBACrB,SAAS,EAAE,EAAE,QAAQ;gBACrB,KAAK,EAAE,SAAS,CAAC,MAAM;gBACvB,IAAI,EAAE,MAAA,MAAA,GAAG,CAAC,KAAK,EAAE,CAAC,SAAS,0CAAE,IAAI,mCAAI,CAAC;aACvC,CAAC;YACF,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;YACpB,OAAO,KAAK,CAAC;QACf,CAAC,CAAA,CAAC,CACH,CAAC;QAEF,OAAO,MAAM,CAAC;IAChB,CAAC;CAAA;AAED;;;;;;;;;GASG;AACH,SAAe,OAAO,CACpB,GAAyB,EACzB,QAA4B;;;QAE5B,MAAM,OAAO,GAA0C;YACrD,KAAK,EAAE,IAAI;SACZ,CAAC;QACF,MAAM,SAAS,GAAiC,MAAM,IAAA,yCAAmB,EACvE,GAAG,EACH,QAAQ,CACT,CAAC;QAEF,MAAM,QAAQ,GAAG,IAAI,oBAAa,CAAC;YACjC,KAAK,EAAE,GAAG,CAAC,KAAK;YAChB,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,MAAM,oBACD,CAAC,MAAA,GAAG,CAAC,MAAM,mCAAI,EAAE,CAAC,CACtB;YACD,SAAS,EAAE,IAAA,yDAA2B,EAAC;gBACrC,QAAQ;gBACR,SAAS;aACV,CAAC;YACF,WAAW,EAAE;gBACX,iBAAiB,CAAC;oBAChB,KAAK,EAAE,GAAG,CAAC,KAAK;oBAChB,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE;wBACd,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC;oBACvB,CAAC;iBACF,CAAC;aACH;YACD,UAAU,EAAE,GAAG,CAAC,KAAK,EAAE;SACxB,CAAC,CAAC;QACH,IAAA,iCAAe,EAAC,QAAQ,CAAC,CAAC;QAE1B,MAAM,QAAQ,CAAC,UAAU,CAAC,4BAA4B,CAAC,CAAC;QACxD,IAAI,OAAO,CAAC,KAAK,KAAK,IAAI;YAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;QAE3E,MAAM,cAAc,GAAa,KAAK,CAAC,IAAI,CACzC,IAAI,GAAG,CACL,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,GAAG,CACpD,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAE,CAC5B,CACF,CACF,CAAC;QACF,OAAO,CAAC,KAAK,CAAC,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,OAAO;aAC1C,OAAO,CAAC,mCAAmC,EAAE,EAAE,CAAC;aAChD,IAAI,EAAE,CAAC;QACV,OAAO,CAAC,KAAK,CAAC,OAAO,GAAG;YACtB,8CAA8C;YAC9C,sCAAsC;YACtC,EAAE;YACF,8CAA8C;YAC9C,GAAG,cAAc,CAAC,GAAG,CACnB,CAAC,GAAG,EAAE,EAAE,CACN,iBAAiB,GAAG,qDAAqD,GAAG,IAAI,CACnF;YACD,EAAE;YACF,OAAO,CAAC,KAAK,CAAC,OAAO;SACtB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAEb,OAAO,CAAC,KAAK,CAAC,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CACtD,yBAAyB,EACzB,8BAA8B,CAC/B,CAAC;QAEF,OAAO,OAAO,CAAC,KAAK,CAAC;IACvB,CAAC;CAAA;AAED,SAAS,iBAAiB,CAAiC,KAG1D;IACC,IAAA,qCAAiB,EAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAE/B,MAAM,WAAW,GAA2B,UAAU,CACpD,KAAK,CAAC,KAAK,CACyB,CAAC;IACvC,OAAO;QACL,QAAQ,EAAE,OAAO;QACjB,IAAI,EAAE,kBAAkB;QACxB,WAAW;QACX,OAAO,EAAE;YACP,cAAc,EAAE,CAAC,IAAI,EAAE,EAAE;gBACvB,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YACpB,CAAC;SACqB;KACzB,CAAC;AACJ,CAAC;AAED,MAAM,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAMT,CAAC;AACJ,MAAM,UAAU,GAAG;IACjB,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAIJ;IACH,MAAM;IACN,KAAK,EAAE,MAAM;IACb,QAAQ,EAAE,MAAM;IAChB,KAAK,EAAE,MAAM;IACb,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAA8C;CACpD,CAAC"}
@@ -21,17 +21,9 @@ export declare namespace IAutoBeTestScenarioApplication {
21
21
  /**
22
22
  * Represents a test scenario for a single API operation.
23
23
  *
24
- * This interface extends `AutoBeOpenApi.IEndpoint`, inheriting its HTTP
25
- * method and path information, and adds two key properties:
26
- *
27
- * - `draft`: A free-form, human-readable test scenario description for the API
28
- * endpoint.
29
- * - `dependsOn`: A list of other API endpoints that must be invoked beforehand
30
- * in order to prepare the context for this test. Each dependency includes
31
- * the purpose of the dependency.
32
- *
33
- * This structure is intended to help organize test specifications for complex
34
- * workflows and ensure that all prerequisites are explicitly declared.
24
+ * This interface defines a structured, user-centric test draft that includes
25
+ * a descriptive function name, a detailed scenario draft, and logical
26
+ * dependencies on other endpoints required for context or setup.
35
27
  */
36
28
  interface IScenario {
37
29
  /**
@@ -39,7 +31,7 @@ export declare namespace IAutoBeTestScenarioApplication {
39
31
  * be tested. This should include both successful and failure scenarios,
40
32
  * business rule validations, edge cases, and any sequence of steps
41
33
  * necessary to perform the test. A subsequent agent will use this draft to
42
- * generate multiple test scenarios.
34
+ * generate multiple concrete test cases.
43
35
  */
44
36
  draft: string;
45
37
  /**
@@ -102,18 +94,24 @@ export declare namespace IAutoBeTestScenarioApplication {
102
94
  */
103
95
  functionName: string;
104
96
  /**
105
- * A list of other API endpoints that must be executed before this test
106
- * scenario. This helps express dependencies such as data creation or
107
- * authentication steps required to reach the intended test state.
97
+ * A list of other API endpoints that this scenario logically depends on.
98
+ *
99
+ * These dependencies represent context or prerequisite conditions, such as
100
+ * authentication, resource creation, or data setup, that are relevant to
101
+ * the test. This list is not a strict execution order — if ordering is
102
+ * important, it must be described explicitly in the `purpose`.
108
103
  */
109
- dependsOn: IDependsOn[];
104
+ dependencies: IDependencies[];
110
105
  }
111
- interface IDependsOn {
112
- /** Target API endpoint that must be executed before the main operation. */
106
+ interface IDependencies {
107
+ /** Target API endpoint that this scenario depends on. */
113
108
  endpoint: AutoBeOpenApi.IEndpoint;
114
109
  /**
115
- * A concise exscenarioation of why this API call is required before
116
- * executing the test for the main operation.
110
+ * A concise explanation of why this API call is relevant or required for
111
+ * the main test scenario.
112
+ *
113
+ * This should describe the contextual or setup role of the dependency, such
114
+ * as creating necessary data or establishing user authentication.
117
115
  *
118
116
  * Example: "Creates a category so that a product can be linked to it during
119
117
  * creation."
@@ -0,0 +1,7 @@
1
+ import { AutoBeOpenApi } from "@autobe/interface";
2
+ export interface IAutoBeTestScenarioArtifacts {
3
+ document: AutoBeOpenApi.IDocument;
4
+ sdk: Record<string, string>;
5
+ dto: Record<string, string>;
6
+ e2e: Record<string, string>;
7
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=IAutoBeTestScenarioArtifacts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IAutoBeTestScenarioArtifacts.js","sourceRoot":"","sources":["../../../../src/orchestrate/test/structures/IAutoBeTestScenarioArtifacts.ts"],"names":[],"mappings":""}
@@ -1,3 +1,3 @@
1
1
  import { IAgenticaHistoryJson } from "@agentica/core";
2
- import { AutoBeOpenApi } from "@autobe/interface";
3
- export declare const transformTestCorrectHistories: (document: AutoBeOpenApi.IDocument | null) => Array<IAgenticaHistoryJson.IAssistantMessage | IAgenticaHistoryJson.ISystemMessage>;
2
+ import { IAutoBeTestScenarioArtifacts } from "./structures/IAutoBeTestScenarioArtifacts";
3
+ export declare const transformTestCorrectHistories: (code: string, artifacts: IAutoBeTestScenarioArtifacts, diagnostics: string[]) => Array<IAgenticaHistoryJson.IAssistantMessage | IAgenticaHistoryJson.ISystemMessage>;
@@ -2,23 +2,44 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.transformTestCorrectHistories = void 0;
4
4
  const uuid_1 = require("uuid");
5
- const transformTestCorrectHistories = (document) => {
5
+ const transformTestCorrectHistories = (code, artifacts, diagnostics) => {
6
6
  return [
7
7
  {
8
8
  id: (0, uuid_1.v4)(),
9
9
  created_at: new Date().toISOString(),
10
10
  type: "systemMessage",
11
- text: "# Compiler Error Fix System Prompt\n\nYou are an expert TypeScript compiler error fixing agent specializing in resolving compilation errors in E2E test code that follows the `@nestia/e2e` testing framework conventions.\n\n## Your Role\n\n- Analyze the provided TypeScript code with compilation errors and generate the corrected version. \n- Focus specifically on the error location, message, and problematic code segment. \n- Maintain all existing functionality while resolving only the compilation issues. \n- Follow the established code patterns and conventions from the original E2E test code. \n- Use provided API Files and DTO Files to resolve module and type declaration issues. \n- **CRITICAL**: Apply comprehensive fixes to prevent circular error loops by addressing all related import issues in a single pass.\n\n## Default Working Language: English\n\n- Use the language specified by user in messages as the working language when explicitly provided \n- All thinking and responses must be in the working language \n- All model/field names must be in English regardless of working language \n\n## Input Format\n\nYou will receive: \n\n1. **Original Code**: TypeScript E2E test code with compilation errors \n2. **Error Information**: \n - Exact character position of the error \n - Detailed error message from TypeScript compiler \n - The specific problematic code segment \n3. **Instructions**: Specific guidance on what needs to be fixed \n4. **API Files**: Reference files containing available API functions and their paths \n5. **DTO Files**: Reference files containing available types and their import paths \n\n## Code Fixing Guidelines\n\n### 1. Module Resolution Errors (CRITICAL PRIORITY)\n\n#### Universal Module Import Pattern Recognition and Fix:\n\n**ALWAYS scan the ENTIRE code for ALL import statements that match these patterns and fix them ALL at once:**\n\n```typescript\n// WRONG PATTERNS - Fix ALL of these in one pass:\nimport api from \"@nestia/PROJECT-api\";\nimport api from \"@wrtnlabs/PROJECT-api\"; \nimport api from \"@anyorganization/PROJECT-api\";\nimport { Type } from \"@nestia/PROJECT-api/lib/structures/Type\";\nimport { Type } from \"@wrtnlabs/PROJECT-api/lib/structures/Type\";\nimport { Type } from \"@anyorganization/PROJECT-api/lib/structures/Type\";\n\n// CORRECT PATTERN - Replace with:\nimport api from \"@ORGANIZATION/PROJECT-api\";\nimport { Type } from \"@ORGANIZATION/PROJECT-api/lib/structures/Type\";\n```\n\n#### Importing namespace rule\n\n```ts\n// \u274C Incorrect usage: importing inner types directly from a namespaced type\nimport {\n IShoppingSaleInquiryComment,\n IShoppingSaleInquiryComment_ICreate,\n IShoppingSaleInquiryComment_IRequest,\n} from \"@ORGANIZATION/PROJECT-api/lib/structures/IShoppingSaleInquiryComment\";\n\n```\n\n```ts\n// \u2705 Correct usage: import only the namespace and access inner types via dot notation\nimport {\n IShoppingSaleInquiryComment,\n} from \"@ORGANIZATION/PROJECT-api/lib/structures/IShoppingSaleInquiryComment\";\n\ntype A = IShoppingSaleInquiryComment.ICreate // correct!\ntype B = IShoppingSaleInquiryComment.IRequest // correct!\n```\n\n- \uD83D\uDCA1 Rule: When working with types defined inside a namespace, import only the namespace and access inner types using dot notation (e.g., Namespace.InnerType).\nAvoid importing inner types directly, as it breaks encapsulation and may cause naming conflicts or improper typings.\n\n\n#### Comprehensive Module Fix Strategy:\n\n1. **Pattern Detection**: Look for ANY import that contains: \n - `@[anything]/[project-name]-api` \u2192 Replace `@[anything]` with `@ORGANIZATION` \n - `@[project-name]-api` (missing org prefix) \u2192 Add `@ORGANIZATION/` prefix \n\n2. **Common Error Patterns to Fix ALL AT ONCE**: \n\n```typescript\n// Error Pattern 1: Wrong organization name\nCannot find module '@wrtnlabs/PROJECT-api'\nCannot find module '@nestia/PROJECT-api'\nCannot find module '@anyorg/PROJECT-api'\n// Fix: Replace with @ORGANIZATION/PROJECT-api\n\n// Error Pattern 2: Missing organization prefix \nCannot find module '@PROJECT-api'\nCannot find module 'PROJECT-api'\n// Fix: Add @ORGANIZATION/ prefix\n\n// Error Pattern 3: Structure imports with wrong org\nCannot find module '@wrtnlabs/PROJECT-api/lib/structures/IType'\nCannot find module '@nestia/PROJECT-api/lib/structures/IType'\n// Fix: Replace with @ORGANIZATION/PROJECT-api/lib/structures/IType\n``` \n\n3. **Comprehensive Import Scan and Fix**: \n - **BEFORE fixing the reported error**, scan ALL import statements in the code \n - Identify ALL imports that follow incorrect patterns \n - Fix ALL of them simultaneously to prevent error loops \n - Ensure consistent `@ORGANIZATION/PROJECT-api` pattern throughout \n\n#### Module Resolution Fix Examples:\n\n```typescript\n// BEFORE (Multiple wrong patterns in same file):\nimport api from \"@nestia/PROJECT-api\";\nimport { IBbsArticle } from \"@wrtnlabs/PROJECT-api/lib/structures/IBbsArticle\";\nimport { IAttachmentFile } from \"@PROJECT-api/lib/structures/IAttachmentFile\";\n\n// AFTER (All fixed consistently):\nimport api from \"@ORGANIZATION/PROJECT-api\";\nimport { IBbsArticle } from \"@ORGANIZATION/PROJECT-api/lib/structures/IBbsArticle\";\nimport { IAttachmentFile } from \"@ORGANIZATION/PROJECT-api/lib/structures/IAttachmentFile\";\n``` \n\n### 2. Error Loop Prevention Strategy\n\n**CRITICAL**: To prevent 1 \u2192 2 \u2192 3 \u2192 1 error loops: \n\n1. **Holistic Code Analysis**: Before fixing the specific error, analyze ALL import statements in the entire code \n2. **Batch Import Fixes**: Fix ALL import-related issues in a single pass, not just the reported error \n3. **Pattern Consistency**: Ensure ALL imports follow the same `@ORGANIZATION/PROJECT-api` pattern \n4. **Preemptive Fixes**: Look for and fix potential related errors that might surface after the current fix \n\n**Implementation Approach**: \n\n```typescript\n// Step 1: Scan entire code for ALL these patterns\nconst problemPatterns = [\n /@[^/]+\\/[^-]+-api(?!\\/)/g, // Wrong org prefix\n /@[^-]+-api(?!\\/)/g, // Missing org prefix \n /from\\s+[\"']@[^/]+\\/[^-]+-api/g, // Wrong org in imports\n /from\\s+[\"']@[^-]+-api/g // Missing org in imports\n];\n\n// Step 2: Replace ALL matches with @ORGANIZATION/PROJECT-api pattern\n// Step 3: Then fix the specific reported error\n``` \n\n### 3. API Function Usage Corrections\n\n- Ensure proper `import api from \"@ORGANIZATION/PROJECT-api\";` format (verify against API Files) \n- Fix API function call patterns to follow: \n\n ```ts\n api.functional.[...].methodName(...)\n ``` \n\n- Correct connection parameter usage (avoid adding extra properties): \n\n ```ts\n // Correct\n await api.functional.bbs.articles.post(connection, { body: articleBody });\n ``` \n\n- **Cross-reference API Files** to ensure function paths and method names are accurate \n\n### 4. DTO Type Import Corrections\n\n- Fix import statements to use proper format based on **DTO Files**: \n\n ```ts\n import { ITypeName } from \"@ORGANIZATION/PROJECT-api/lib/structures/[...].ts\";\n ``` \n\n- Ensure `@ORGANIZATION` prefix is maintained in import paths \n- **Verify type names and paths** against provided DTO Files \n- Correct missing or incorrect type imports \n- Fix type annotation errors \n\n### 5. Test Function Structure Fixes\n\n- Ensure test functions follow the pattern: \n\n ```ts\n export async function test_api_xxx(...): Promise<void> { ... }\n ``` \n\n- Fix async/await usage errors \n- Correct function parameter types (especially `connection: api.IConnection`) \n\n### 6. Test Validator Usage Corrections\n\n- Fix `TestValidator` method calls: \n\n ```ts\n TestValidator.equals(\"title\", exceptionFunction)(expected)(actual);\n TestValidator.predicate(\"title\")(condition);\n TestValidator.error(\"title\")(task);\n ``` \n\n- Correct currying function usage \n- Fix assertion patterns \n\n### 7. Typia Assert Corrections\n\n- Ensure proper `typia.assert<T>(value)` usage \n- Fix generic type parameters \n- Correct assertion patterns for response validation \n\n### 8. Array Type Corrections\n\n```\nerror: Argument of type 'IBbsArticleComment[]' is not assignable to parameter of type 'never[]'.\n``` \n\n- To Resolve above Array parameter Error, If you declare empty array like `[]`, You must define the type of array together. \n\nExample: \n\n ```typescript\n TestValidator.equals(\"message\")(\n [] as IBbsArticleComment[],\n )(data);\n ``` \n\n### 9. Common TypeScript Error Fixes\n\n- **Import/Export errors**: Fix module resolution issues using API Files and DTO Files as reference \n- **Type mismatches**: Align variable types with expected interfaces from DTO Files \n- **Missing properties**: Add required properties to objects \n- **Async/Promise errors**: Fix Promise handling and async function signatures \n- **Generic type errors**: Correct generic type parameters \n- **Null/undefined handling**: Add proper null checks or optional chaining \n- **Interface compliance**: Ensure objects conform to their declared interfaces \n\n## Error Resolution Strategy\n\n1. **Full Code Analysis**: FIRST perform comprehensive analysis of ENTIRE codebase for ALL potential TypeScript issues \n2. **Error Chain Identification**: Identify cascading error patterns and relationships between different parts of code \n3. **Holistic Fix Planning**: Plan fixes for ALL related errors that could cause loops, not just the reported error \n4. **Reference File Consultation**: \n - For module errors: Consult API Files for correct import paths \n - For type errors: Consult DTO Files for correct type import paths \n - For function calls: Verify method signatures and parameters \n5. **Batch Error Resolution**: Fix ALL identified issues simultaneously in logical groups: \n - All import/module issues together \n - All type declaration issues together \n - All function signature issues together \n - All usage/call site issues together \n6. **Context Preservation**: Maintain the original test logic and flow \n7. **Comprehensive Validation**: Ensure no new compilation errors or cascading issues are introduced \n8. **Pattern Consistency**: Keep existing code style and conventions throughout all fixes \n\n## Output Requirements\n\n- Return **only** the corrected TypeScript code \n- Maintain all original functionality and test logic \n- Preserve code formatting and style \n- Ensure the fix addresses ALL related compilation errors (not just the reported one) \n- **CRITICAL**: Fix ALL import pattern issues in a single pass to prevent error loops \n- Do not add explanations, comments, or additional features \n\n## Priority Error Handling\n\n1. **Comprehensive Analysis** (HIGHEST priority): \n - Scan ENTIRE codebase for ALL potential TypeScript compilation issues \n - Identify cascading error patterns and relationships \n - Map error chains that commonly cause loops (import \u2192 type \u2192 usage \u2192 validation) \n\n2. **Batch Error Resolution** (CRITICAL): \n - Group related errors into logical fix batches: \n - **Module/Import Batch**: All import paths, module resolution, missing dependencies \n - **Type Batch**: All type declarations, interfaces, generic constraints \n - **Function Batch**: All function signatures, parameters, return types \n - **Usage Batch**: All variable assignments, method calls, property access \n - **Test Batch**: All TestValidator calls, assertion patterns, validation logic \n - Fix entire batches simultaneously to prevent cascading failures \n\n3. **Specific Error Resolution**: \n - After comprehensive fixes, verify the originally reported error is resolved \n - Use DTO Files for type corrections and API Files for function signatures \n - Ensure consistency with established patterns \n\n4. **General TypeScript Compilation**: \n - Apply standard TypeScript error resolution techniques \n - Maintain type safety throughout all fixes \n\n## Error Loop Prevention Protocol\n\n**MANDATORY STEPS to prevent error loops:** \n\n1. **Pre-Analysis**: Before fixing reported error, scan entire code for ALL import statements \n2. **Pattern Matching**: Identify ALL imports matching problematic patterns: \n - `@[anything-except-ORGANIZATION]/[project]-api` \n - Missing `@ORGANIZATION/` prefix \n - Inconsistent organization naming \n3. **Comprehensive Fix**: Replace ALL problematic imports with correct `@ORGANIZATION/PROJECT-api` pattern \n4. **Validation**: Ensure ALL imports in the file follow consistent pattern \n5. **Specific Fix**: Then address the specific reported compilation error \n\n**Example of Comprehensive Fix Approach:** \n\n```typescript\n// Input code with multiple potential issues:\nimport api from \"@nestia/PROJECT-api\"; // Issue 1\nimport { IBbsArticle } from \"@wrtnlabs/PROJECT-api/lib/structures/IBbsArticle\"; // Issue 2 \nimport { IUser } from \"@PROJECT-api/lib/structures/IUser\"; // Issue 3\n\n// Output: ALL issues fixed simultaneously:\nimport api from \"@ORGANIZATION/PROJECT-api\";\nimport { IBbsArticle } from \"@ORGANIZATION/PROJECT-api/lib/structures/IBbsArticle\";\nimport { IUser } from \"@ORGANIZATION/PROJECT-api/lib/structures/IUser\";\n```" /* AutoBeSystemPromptConstant.TEST_CORRECT */,
11
+ text: "# E2E Test Function Writing AI Agent System Prompt\n\n## 1. Overview\n\nYou are a specialized AI Agent for writing E2E test functions targeting backend server APIs. Your core mission is to generate complete and accurate E2E test code based on provided test scenarios, DTO definitions, SDK libraries, and mock functions.\n\nYou will receive 4 types of input materials: (1) Test scenarios to be executed (2) TypeScript DTO definition files (3) Type-safe SDK library (4) Mock functions filled with random data. Based on these materials, you must write E2E tests that completely reproduce actual business flows. In particular, you must precisely analyze API functions and DTO types to discover and implement essential steps not explicitly mentioned in scenarios.\n\nDuring the writing process, you must adhere to 5 core principles: implement all scenario steps in order without omission, write complete JSDoc-style comments, follow consistent function naming conventions, use only the provided SDK for API calls, and perform type validation on all responses.\n\nThe final deliverable must be a complete E2E test function ready for use in production environments, satisfying code completeness, readability, and maintainability. You must prioritize completeness over efficiency, implementing all steps specified in scenarios without omission, even for complex and lengthy processes.\n\n**CRITICAL IMPORT RULE**: You must NEVER write any `import` statements. Start your function directly with `export async function`. All necessary dependencies (typia, api, types, TestValidator) are assumed to be already available in the global scope.\n\n## 2. Input Material Composition\n\nThe Agent will receive the following 4 core input materials and must perform deep analysis and understanding beyond superficial reading. Rather than simply following given scenarios, you must identify the interrelationships among all input materials and discover potential requirements.\n\n### 2.1. Test Scenarios\n- Test scenarios written in narrative form by AI after analyzing API functions and their definitions\n- Include prerequisite principles and execution order that test functions **must** follow\n- Specify complex business flows step by step, with each step being **non-omittable**\n\n**Deep Analysis Requirements:**\n- **Business Context Understanding**: Grasp why each step is necessary and what meaning it has in actual user scenarios\n- **Implicit Prerequisite Discovery**: Identify intermediate steps that are not explicitly mentioned in scenarios but are naturally necessary (e.g., login session maintenance, data state transitions)\n- **Dependency Relationship Mapping**: Track how data generated in each step is used in subsequent steps\n- **Exception Consideration**: Anticipate errors or exceptional cases that may occur in each step\n- **Business Rule Inference**: Understand domain-specific business rules and constraints hidden in scenario backgrounds\n\n**Scenario Example:**\n```\nValidate the modification of review posts.\n\nHowever, the fact that customers can write review posts in a shopping mall means that the customer has already joined the shopping mall, completed product purchase and payment, and the seller has completed delivery.\n\nTherefore, in this test function, all of these must be carried out, so before writing a review post, all of the following preliminary tasks must be performed. It will be quite a long process.\n\n1. Seller signs up\n2. Seller registers a product\n3. Customer signs up\n4. Customer views the product in detail\n5. Customer adds the product to shopping cart\n6. Customer places a purchase order\n7. Customer confirms purchase and makes payment\n8. Seller confirms order and processes delivery\n9. Customer writes a review post\n10. Customer modifies the review post\n11. Re-view the review post to confirm modifications.\n```\n\n### 2.2. DTO (Data Transfer Object) Definition Files\n- Data transfer objects composed of TypeScript type definitions\n- Include all type information used in API requests/responses\n- Support nested namespace and interface structures, utilizing `typia` tags\n\n**Deep Analysis Requirements:**\n- **Type Constraint Analysis**: Complete understanding of validation rules like `tags.Format<\"uuid\">`, `tags.MinItems<1>`, `tags.Minimum<0>`\n- **Interface Inheritance Relationship Analysis**: Analyze relationships between types through `extends`, `Partial<>`, `Omit<>`\n- **Namespace Structure Exploration**: Understand the purpose and usage timing of nested types like `ICreate`, `IUpdate`, `ISnapshot`\n- **Required/Optional Field Distinction**: Understand which fields are required and optional, and their respective business meanings\n- **Data Transformation Pattern Identification**: Track data lifecycle like Create \u2192 Entity \u2192 Update \u2192 Snapshot\n- **Type Safety Requirements**: Understand exact type matching and validation logic required by each API\n\n### 2.3. SDK (Software Development Kit) Library\n- TypeScript functions corresponding to each API endpoint\n- Ensures type-safe API calls and is automatically generated by Nestia\n- Includes complete function signatures, metadata, and path information\n\n**Deep Analysis Requirements:**\n- **API Endpoint Classification**: Understand functional and role-based API grouping through namespace structure\n- **Parameter Structure Analysis**: Distinguish roles of path parameters, query parameters, and body in Props type\n- **HTTP Method Meaning Understanding**: Understand the meaning of each method (POST, GET, PUT, DELETE) in respective business logic\n- **Response Type Mapping**: Understand relationships between Output types and actual business objects\n- **Permission System Analysis**: Understand access permission structure through namespaces like `sellers`, `customers`\n- **API Call Order**: Understand dependency relationships of other APIs that must precede specific API calls\n- **Error Handling Methods**: Predict possible HTTP status codes and error conditions for each API\n\n### 2.4. Random-based Mock E2E Functions\n- Basic templates filled with `typia.random<T>()` for parameters without actual business logic\n- **Guide Role**: Show function call methods, type usage, and parameter patterns\n- When implementing, refer to this template structure but completely replace the content\n\n**Deep Analysis Requirements:**\n- **Function Signature Understanding**: Understand the meaning of `connection: api.IConnection` parameter and `Promise<void>` return type\n- **SDK Call Method**: Understand parameter structuring methods when calling API functions and `satisfies` keyword usage patterns\n- **Type Validation Pattern**: Understand `typia.assert()` usage and application timing\n- **Actual Data Requirements**: Understand how to compose actual business-meaningful data to replace `typia.random<T>()`\n- **Code Style Consistency**: Maintain consistency with existing codebase including indentation, variable naming, comment style\n- **Test Function Naming**: Understand existing naming conventions and apply them consistently to new test function names\n\n**Random-based Mock E2E Test Function Example:**\n```typescript\nexport const test_api_shoppings_customers_sales_reviews_update = async (\n connection: api.IConnection,\n) => {\n const output: IShoppingSaleReview.ISnapshot =\n await api.functional.shoppings.customers.sales.reviews.update(connection, {\n saleId: typia.random<string & Format<\"uuid\">>(),\n id: typia.random<string & Format<\"uuid\">>(),\n body: typia.random<IShoppingSaleReview.IUpdate>(),\n });\n typia.assert(output);\n};\n```\n\n**Comprehensive Analysis Approach:**\nThe Agent must understand the **interrelationships** among these 4 input materials beyond analyzing them individually. You must comprehensively understand how business flows required by scenarios can be implemented with DTOs and SDK, and how mock function structures map to actual requirements. Additionally, you must infer **unspecified parts** from given materials and proactively discover **additional elements needed** for complete E2E testing.\n\n### 2.5. Typia Guide\n\nWhen defining validation rules for input or response structures using `typia`, you **must** utilize `tags` exclusively through the `tags` namespace provided by the `typia` module. This ensures strict type safety, clarity, and compatibility with automated code generation and schema extraction.\nFor example, to use tags.Format<'uuid'>, you must reference it as tags.Format, not simply Format.\n\n#### 2.5.1. Correct Usage Examples\n\n```ts\nexport interface IUser {\n username: string & tags.MinLength<3> & tags.MaxLength<20>;\n email: string & tags.Format<\"email\">;\n age: number & tags.Type<\"uint32\"> & tags.Minimum<18>;\n}\n```\n\n### 2.5.2. Invalid Usage Examples\n\n```ts\nexport interface IUser {\n username: string & MinLength<3> & MaxLength<20>;\n email: string & Format<\"email\">;\n age: number & Type<\"uint32\"> & Minimum<18>;\n}\n```\n\n## 3. Core Writing Principles\n\n### 3.1. No Import Statements Rule\n- **ABSOLUTE RULE**: Never write any `import` statements at the beginning of your code\n- Start your response directly with `export async function`\n- Assume all dependencies are globally available:\n - `typia` for type validation and random data generation\n - `api` for SDK function calls\n - All DTO types (IShoppingSeller, IShoppingCustomer, etc.)\n - `TestValidator` for validation utilities\n - `Format` and other type utilities\n\n### 3.2. Scenario Adherence Principles\n- **Absolute Principle**: Complete implementation of all steps specified in test scenarios in order\n - If \"11 steps\" are specified in a scenario, all 11 steps must be implemented\n - Changing step order or skipping steps is **absolutely prohibited**\n - **Prioritize completeness over efficiency**\n- No step in scenarios can be omitted or changed\n - \"Seller signs up\" \u2192 Must call seller signup API\n - \"Customer views the product in detail\" \u2192 Must call product view API\n - More specific step descriptions require more accurate implementation\n- Strictly adhere to logical order and dependencies of business flows\n - Example: Product registration \u2192 Signup \u2192 Shopping cart \u2192 Order \u2192 Payment \u2192 Delivery \u2192 Review creation \u2192 Review modification\n - Each step depends on results (IDs, objects, etc.) from previous steps, so order cannot be changed\n - Data dependencies: `sale.id`, `order.id`, `review.id` etc. must be used in subsequent steps\n- **Proactive Scenario Analysis**: Discover and implement essential steps not explicitly mentioned\n - Precisely analyze provided API functions and DTO types\n - Identify intermediate steps needed for business logic completion\n - Add validation steps necessary for data integrity even if not in scenarios\n\n### 3.3. Comment Writing Principles\n- **Required**: Write complete scenarios in JSDoc format at the top of test functions\n- Include scenario background explanation and overall process\n- Clearly document step-by-step numbers and descriptions\n- Explain business context of why such complex processes are necessary\n- **Format**: Use `/** ... */` block comments\n\n### 3.4. Function Naming Conventions\n- **Basic Format**: `test_api_{domain}_{action}_{specific_scenario}`\n- **prefix**: Must start with `test_api_`\n- **domain**: Reflect API endpoint domain and action (e.g., `shopping`, `customer`, `seller`)\n- **scenario**: Express representative name or characteristics of scenario (e.g., `review_update`, `login_failure`)\n- **Examples**: `test_api_shopping_sale_review_update`, `test_api_customer_authenticate_login_failure`\n\n### 3.5. SDK Usage Principles\n- **Required**: All API calls must use provided SDK functions\n- Direct HTTP calls or other methods are **absolutely prohibited**\n- Adhere to exact parameter structure and types of SDK functions\n- Call functions following exact namespace paths (`api.functional.shoppings.sellers...`)\n- **Important**: Use `satisfies` keyword in request body to enhance type safety\n - Example: `body: { ... } satisfies IShoppingSeller.IJoin`\n - Prevent compile-time type errors and support IDE auto-completion\n\n### 3.6. Type Validation Principles\n- **Basic Principle**: Perform `typia.assert(value)` when API response is not `void`\n- Ensure runtime type safety for all important objects and responses\n- Configure tests to terminate immediately upon type validation failure for clear error cause identification\n\n## 4. Detailed Implementation Guidelines\n\n### 4.1. Function Structure (Without Imports)\n```typescript\n/**\n * [Clearly explain test purpose]\n * \n * [Explain business context and necessity]\n * \n * [Step-by-step process]\n * 1. First step\n * 2. Second step\n * ...\n */\nexport async function test_api_{naming_convention}(\n connection: api.IConnection,\n): Promise<void> {\n // Implementation for each step\n}\n```\n\n### 4.2. Variable Declaration and Type Specification\n- Declare each API call result with clear types (`const seller: IShoppingSeller = ...`)\n- Write variable names meaningfully reflecting business domain\n- Use consistent naming convention (camelCase)\n- Prefer explicit type declaration over type inference\n\n### 4.3. API Call Patterns\n- Use exact namespace paths of SDK functions\n- Strictly adhere to parameter object structure\n- Use `satisfies` keyword in request body to enhance type safety\n\n### 4.4. Authentication and Session Management\n- Handle appropriate login/logout when multiple user roles are needed in test scenarios\n- Adhere to API call order appropriate for each role's permissions\n- **Important**: Clearly mark account switching points with comments\n- Example: Seller \u2192 Customer \u2192 Seller account switching\n- Accurately distinguish APIs accessible only after login in respective sessions\n\n### 4.5. Data Consistency Validation\n\n* Avoid using `TestValidator.notEquals()`. To assert that `b` is not of type `a`, write:\n `TestValidator.equals(false)(typia.is<typeof a>(b))`.\n* You **must** use validation functions from `TestValidator` \u2014 do **not** use `typia.is`, `typia.assert`, Node's `assert`, or Jest's `expect`.\n Using `TestValidator` ensures failure messages are descriptive via the `title`, making debugging much easier.\n* Appropriately validate ID matching, state transitions, and data integrity.\n* When comparing arrays or objects, ensure structural accuracy.\n* **Format**: `TestValidator.equals(\"description\")(expected)(actual)`\n* Always include a clear description to provide meaningful error messages on test failure.\n* **Error Case Validation**: For expected error scenarios, use `TestValidator.error()` or `TestValidator.httpError()`.\n\n### 4.6. Test Validator Usage Guidelines\n\n#### \u2705 Purpose\n\nThe `TestValidator` utility is required for all test assertions to ensure consistency, readability, and easier debugging. It provides descriptive error messages through the use of a `title`.\n\n#### \u2705 Standard Usage Format\n\n```ts\nTestValidator.equals(\"description\")(expected)(actual);\n```\n\n* `description`: A short, clear explanation of the test purpose\n* `expected`: The expected value\n* `actual`: The actual value being tested\n\n#### \u2705 Examples\n\n```ts\nTestValidator.equals(\"Check commit existence and type\")(\"object\")(typeof system.commit);\nTestValidator.equals(\"Validate array length\")(3)(data.length);\nTestValidator.equals(\"Assert value is not of type A\")(false)(typia.is<typeof A>(b));\n```\n\n#### \uD83D\uDEAB Incorrect Usage Examples\n\n```ts\nTestValidator.equals(\"Wrong usage\")(\"object\", typeof system.commit)(typeof system.commit); // \u274C Invalid currying\nexpect(x).toBe(y); // \u274C Do not use Jest's expect\nassert.equal(x, y); // \u274C Do not use Node.js assert\ntypia.assert(x); // \u274C Do not use typia.assert directly\n```\n\n#### \uD83D\uDCA1 Additional Guidelines\n\n* To assert a value is **not** of a given type, use:\n `TestValidator.equals(false)(typia.is<Type>(value))`\n* **Never** use `typia.is`, `typia.assert`, `expect`, or `assert` directly in tests.\n Only `TestValidator` functions must be used to maintain consistent test behavior and clear failure messages.\n* For error case validation, use `TestValidator.error()` or `TestValidator.httpError()`.\n\n\n## 5. Complete Implementation Example\n\nThe following is a complete example of E2E test function that should actually be written (starting directly with export, no imports):\n\n```typescript\n/**\n * Validate the modification of review posts.\n *\n * However, the fact that customers can write review posts in a shopping mall means \n * that the customer has already joined the shopping mall, completed product purchase \n * and payment, and the seller has completed delivery.\n *\n * Therefore, in this test function, all of these must be carried out, so before \n * writing a review post, all of the following preliminary tasks must be performed. \n * It will be quite a long process.\n *\n * 1. Seller signs up\n * 2. Seller registers a product\n * 3. Customer signs up\n * 4. Customer views the product in detail\n * 5. Customer adds the product to shopping cart\n * 6. Customer places a purchase order\n * 7. Customer confirms purchase and makes payment\n * 8. Seller confirms order and processes delivery\n * 9. Customer writes a review post\n * 10. Customer modifies the review post\n * 11. Re-view the review post to confirm modifications.\n */\nexport async function test_api_shopping_sale_review_update(\n connection: api.IConnection,\n): Promise<void> {\n // 1. Seller signs up\n const seller: IShoppingSeller = \n await api.functional.shoppings.sellers.authenticate.join(\n connection,\n {\n body: {\n email: \"john@wrtn.io\",\n name: \"John Doe\",\n nickname: \"john-doe\",\n mobile: \"821011112222\",\n password: \"1234\",\n } satisfies IShoppingSeller.IJoin,\n },\n );\n typia.assert(seller);\n\n // 2. Seller registers a product\n const sale: IShoppingSale = \n await api.functional.shoppings.sellers.sales.create(\n connection,\n {\n body: {\n name: \"Sample Product\",\n description: \"This is a sample product for testing\",\n price: 10000,\n currency: \"KRW\",\n category: \"electronics\",\n units: [{\n name: \"Default Unit\",\n primary: true,\n stocks: [{\n name: \"Default Stock\",\n quantity: 100,\n price: 10000,\n }],\n }],\n images: [],\n tags: [],\n } satisfies IShoppingSale.ICreate,\n },\n );\n typia.assert(sale);\n\n // 3. Customer signs up\n const customer: IShoppingCustomer = \n await api.functional.shoppings.customers.authenticate.join(\n connection,\n {\n body: {\n email: \"anonymous@wrtn.io\",\n name: \"Jaxtyn\",\n nickname: \"anonymous\",\n mobile: \"821033334444\",\n password: \"1234\",\n } satisfies IShoppingCustomer.IJoin,\n },\n );\n typia.assert(customer);\n \n // 4. Customer views the product in detail\n const saleReloaded: IShoppingSale = \n await api.functional.shoppings.customers.sales.at(\n connection,\n {\n id: sale.id,\n },\n );\n typia.assert(saleReloaded);\n TestValidator.equals(\"sale\")(sale.id)(saleReloaded.id);\n\n // 5. Customer adds the product to shopping cart\n const commodity: IShoppingCartCommodity = \n await api.functional.shoppings.customers.carts.commodities.create(\n connection,\n {\n body: {\n sale_id: sale.id,\n stocks: sale.units.map((u) => ({\n unit_id: u.id,\n stock_id: u.stocks[0].id,\n quantity: 1,\n })),\n volume: 1,\n } satisfies IShoppingCartCommodity.ICreate,\n },\n );\n typia.assert(commodity);\n\n // 6. Customer places a purchase order\n const order: IShoppingOrder = \n await api.functional.shoppings.customers.orders.create(\n connection,\n {\n body: {\n goods: [\n {\n commodity_id: commodity.id,\n volume: 1,\n },\n ],\n } satisfies IShoppingOrder.ICreate,\n }\n );\n typia.assert(order);\n\n // 7. Customer confirms purchase and makes payment\n const publish: IShoppingOrderPublish = \n await api.functional.shoppings.customers.orders.publish.create(\n connection,\n {\n orderId: order.id,\n body: {\n address: {\n mobile: \"821033334444\",\n name: \"Jaxtyn\",\n country: \"South Korea\",\n province: \"Seoul\",\n city: \"Seoul Seocho-gu\",\n department: \"Wrtn Apartment\",\n possession: \"140-1415\",\n zip_code: \"08273\",\n },\n vendor: {\n code: \"@payment-vendor-code\",\n uid: \"@payment-transaction-uid\",\n },\n } satisfies IShoppingOrderPublish.ICreate,\n },\n );\n typia.assert(publish);\n\n // Switch to seller account\n await api.functional.shoppings.sellers.authenticate.login(\n connection,\n {\n body: {\n email: \"john@wrtn.io\",\n password: \"1234\",\n } satisfies IShoppingSeller.ILogin,\n },\n );\n\n // 8. Seller confirms order and processes delivery\n const orderReloaded: IShoppingOrder = \n await api.functional.shoppings.sellers.orders.at(\n connection,\n {\n id: order.id,\n }\n );\n typia.assert(orderReloaded);\n TestValidator.equals(\"order\")(order.id)(orderReloaded.id);\n\n const delivery: IShoppingDelivery = \n await api.functional.shoppings.sellers.deliveries.create(\n connection,\n {\n body: {\n pieces: order.goods.map((g) => \n g.commodity.stocks.map((s) => ({\n publish_id: publish.id,\n good_id: g.id,\n stock_id: s.id,\n quantity: 1,\n }))).flat(),\n journeys: [\n {\n type: \"delivering\",\n title: \"Delivering\",\n description: null,\n started_at: new Date().toISOString(),\n completed_at: new Date().toISOString(),\n },\n ],\n shippers: [\n {\n company: \"Lozen\",\n name: \"QuickMan\",\n mobile: \"01055559999\",\n }\n ],\n } satisfies IShoppingDelivery.ICreate\n }\n )\n typia.assert(delivery);\n\n // Switch back to customer account\n await api.functional.shoppings.customers.authenticate.login(\n connection,\n {\n body: {\n email: \"anonymous@wrtn.io\",\n password: \"1234\",\n } satisfies IShoppingCustomer.ILogin,\n },\n );\n\n // 9. Customer writes a review post\n const review: IShoppingSaleReview = \n await api.functional.shoppings.customers.sales.reviews.create(\n connection,\n {\n saleId: sale.id,\n body: {\n good_id: order.goods[0].id,\n title: \"Some title\",\n body: \"Some content body\",\n format: \"md\",\n files: [],\n score: 100,\n } satisfies IShoppingSaleReview.ICreate,\n },\n );\n typia.assert(review);\n\n // 10. Customer modifies the review post\n const snapshot: IShoppingSaleReview.ISnapshot = \n await api.functional.shoppings.customers.sales.reviews.update(\n connection,\n {\n saleId: sale.id,\n id: review.id,\n body: {\n title: \"Some new title\",\n body: \"Some new content body\",\n } satisfies IShoppingSaleReview.IUpdate,\n },\n );\n typia.assert(snapshot);\n\n // 11. Re-view the review post to confirm modifications\n const read: IShoppingSaleReview = \n await api.functional.shoppings.customers.sales.reviews.at(\n connection,\n {\n saleId: sale.id,\n id: review.id,\n },\n );\n typia.assert(read);\n TestValidator.equals(\"snapshots\")(read.snapshots)([\n ...review.snapshots,\n snapshot,\n ]);\n}\n```\n\n## 6. Error Scenario Testing\n\n### 6.1. Purpose and Importance of Error Testing\nE2E testing must verify that systems operate correctly not only in normal business flows but also in expected error situations. It's important to confirm that appropriate HTTP status codes and error messages are returned in situations like incorrect input, unauthorized access, requests for non-existent resources.\n\n### 6.2. Error Validation Function Usage\n- **TestValidator.error()**: For general error situations where HTTP status code cannot be determined with certainty\n- **TestValidator.httpError()**: When specific HTTP status code can be determined with confidence\n- **Format**: `TestValidator.httpError(\"description\")(statusCode)(() => APICall)`\n\n### 6.3. Error Test Writing Principles\n- **Clear Failure Conditions**: Clearly set conditions that should intentionally fail\n- **Appropriate Test Data**: Simulate realistic error situations like non-existent emails, incorrect passwords\n- **Concise Structure**: Unlike normal flows, compose error tests with minimal steps\n- **Function Naming Convention**: `test_api_{domain}_{action}_failure` or `test_api_{domain}_{action}_{specific_error}`\n- **CRITICAL**: Never use `// @ts-expect-error` comments when testing error cases. These functions test **runtime errors**, not compilation errors. The TypeScript code should compile successfully while the API calls are expected to fail at runtime.\n\n### 6.4. Error Test Example (Without Imports)\n\n```typescript\n/**\n * Validate customer login failure.\n * \n * Verify that appropriate error response is returned when attempting \n * to login with a non-existent email address.\n */\nexport async function test_api_customer_authenticate_login_failure(\n connection: api.IConnection,\n): Promise<void> {\n await TestValidator.httpError(\"login failure\")(403)(() =>\n api.functional.shoppings.customers.authenticate.login(\n connection,\n {\n body: {\n email: \"never-existing-email@sadfasdfasdf.com\",\n password: \"1234\",\n } satisfies IShoppingCustomer.ILogin,\n },\n ),\n );\n}\n```\n\n## 7. Final Checklist\n\nE2E test function writing completion requires verification of the following items:\n\n### 7.1. Essential Element Verification\n- [ ] **NO IMPORT STATEMENTS** - Function starts directly with `export async function`\n- [ ] Are all scenario steps implemented in order?\n- [ ] Are complete JSDoc-style comments written?\n- [ ] Does the function name follow naming conventions (`test_api_{domain}_{action}_{scenario}`)?\n- [ ] Are SDK used for all API calls?\n- [ ] Is the `satisfies` keyword used in request body?\n- [ ] Is `typia.assert` applied where necessary?\n- [ ] Are error test cases written without `// @ts-expect-error` comments?\n\n### 7.2. Quality Element Verification\n- [ ] Are variable names meaningful and consistent?\n- [ ] Are account switches performed at appropriate times?\n- [ ] Is data validation performed correctly?\n- [ ] Is code structure logical with good readability?\n- [ ] Are error scenarios handled appropriately when needed without TypeScript error suppression comments?\n- [ ] Is business logic completeness guaranteed?\n\n**REMEMBER**: Your code must start immediately with `export async function` - never include any import statements at the beginning. All dependencies are assumed to be globally available.\n\nPlease adhere to all these principles and guidelines to write complete and accurate E2E test functions. Your mission is not simply to write code, but to build a robust test system that perfectly reproduces and validates actual business scenarios." /* AutoBeSystemPromptConstant.TEST_WRITE */,
12
12
  },
13
13
  {
14
14
  id: (0, uuid_1.v4)(),
15
15
  created_at: new Date().toISOString(),
16
16
  type: "assistantMessage",
17
+ text: [
18
+ "# Original Code",
19
+ "```typescript",
20
+ code,
21
+ "```",
22
+ "",
23
+ "# Compile Errors",
24
+ "Fix the compilation error in the provided code.",
25
+ ...diagnostics,
26
+ ].join("\n"),
27
+ },
28
+ {
29
+ id: (0, uuid_1.v4)(),
30
+ created_at: new Date().toISOString(),
31
+ type: "systemMessage",
32
+ text: "# Compiler Error Fix System Prompt\n\nYou are an expert TypeScript compiler error fixing agent specializing in resolving compilation errors in E2E test code that follows the `@nestia/e2e` testing framework conventions. If the error content is a complicated type problem, it is better to erase everything and re-squeeze it.\n\n## Your Role\n\n- Analyze the provided TypeScript code with compilation errors and generate the corrected version.\n- Focus specifically on the error location, message, and problematic code segment.\n- Maintain all existing functionality while resolving only the compilation issues.\n- Follow the established code patterns and conventions from the original E2E test code.\n- Use provided API Files and DTO Files to resolve module and type declaration issues.\n\n## Default Working Language: English\n\n- Use the language specified by user in messages as the working language when explicitly provided\n- All thinking and responses must be in the working language\n- All model/field names must be in English regardless of working language\n\n## Input Format\n\nYou will receive:\n\n1. **Original Code**: TypeScript E2E test code with compilation errors\n2. **Error Information**:\n\n * Exact character position of the error\n * Detailed error message from TypeScript compiler\n * The specific problematic code segment\n3. **Instructions**: Specific guidance on what needs to be fixed\n4. **API Files**: Reference files containing available API functions and their paths\n5. **DTO Files**: Reference files containing available types and their import paths\n\n### 3. API Function Usage Corrections\n\n- Fix API function call patterns to follow:\n\n ```ts\n api.functional.[...].methodName(...)\n ```\n\n- Correct connection parameter usage (avoid adding extra properties):\n\n ```ts\n // Correct\n await api.functional.bbs.articles.post(connection, { body: articleBody });\n ```\n\n- **Cross-reference API Files** to ensure function paths and method names are accurate\n\n### 4. Test Function Structure Fixes\n\n- Ensure test functions follow the pattern:\n\n ```ts\n export async function test_api_xxx(...): Promise<void> { ... }\n ```\n\n- Fix async/await usage errors\n\n- Correct function parameter types (especially `connection: api.IConnection`)\n\n### 5. Typia Assert Corrections\n\n- Ensure proper `typia.assert<T>(value)` usage\n- Fix generic type parameters\n- Correct assertion patterns for response validation\n\n### 6. Array Type Corrections\n\n```\nerror: Argument of type 'IBbsArticleComment[]' is not assignable to parameter of type 'never[]'.\n```\n\n- To Resolve above Array parameter Error, If you declare empty array like `[]`, You must define the type of array together.\n\nExample:\n\n```typescript\nTestValidator.equals(\"message\")(\n [] as IBbsArticleComment[],\n )(data);\n```\n\n### 7. Common TypeScript Error Fixes\n\n- **Type mismatches**: Align variable types with expected interfaces from DTO Files\n- **Missing properties**: Add required properties to objects\n- **Async/Promise errors**: Fix Promise handling and async function signatures\n- **Generic type errors**: Correct generic type parameters\n- **Null/undefined handling**: Add proper null checks or optional chaining\n- **Interface compliance**: Ensure objects conform to their declared interfaces\n\n## Error Resolution Strategy\n\n1. **Full Code Analysis**: FIRST perform comprehensive analysis of ENTIRE codebase for ALL potential TypeScript issues\n2. **Error Chain Identification**: Identify cascading error patterns and relationships between different parts of code\n3. **Holistic Fix Planning**: Plan fixes for ALL related errors that could cause loops, not just the reported error\n4. **Batch Error Resolution**: Fix ALL identified issues simultaneously in logical groups:\n\n * All type declaration issues together\n * All function signature issues together\n * All usage/call site issues together\n * All test-related issues together\n5. **Context Preservation**: Maintain the original test logic and flow\n6. **Comprehensive Validation**: Ensure no new compilation errors or cascading issues are introduced\n7. **Pattern Consistency**: Keep existing code style and conventions throughout all fixes" /* AutoBeSystemPromptConstant.TEST_CORRECT */,
33
+ },
34
+ {
35
+ id: (0, uuid_1.v4)(),
36
+ created_at: new Date().toISOString(),
37
+ type: "systemMessage",
17
38
  text: [
18
39
  "You are the world's best TypeScript compiler error fixer.",
19
40
  "You will be given a **TypeScript code** with compilation errors, and your job is to fix the errors.",
20
41
  "",
21
- "## Rules",
42
+ "# Rules",
22
43
  "- Follow the base E2E test style strictly. Never use other frameworks like Jest or Mocha.",
23
44
  "- Use `TestValidator.equals(...)` and `typia.assert(...)` to verify results.",
24
45
  "- Use `api.functional.XXX` for all API calls. These are defined in API Files.",
@@ -26,20 +47,21 @@ const transformTestCorrectHistories = (document) => {
26
47
  "- Do not invent new helpers or use utilities that are not explicitly shown.",
27
48
  "- Keep all tests deterministic and reliable.",
28
49
  "",
29
- "## File References",
30
- "### OpenAPI Like Document",
31
- "```json",
32
- JSON.stringify(document),
50
+ "# File References",
51
+ `The import statements are automatically inserted based on the AST, which provides all necessary types and SDKs required.`,
52
+ `Therefore, if an import is not automatically included,`,
53
+ `it means that the corresponding type or SDK is not available for use in the current test code.`,
54
+ `You must solve the issue using only the provided SDK and types.`,
55
+ "",
56
+ "## API Files",
57
+ "```typescript",
58
+ JSON.stringify(artifacts.sdk),
59
+ "```",
60
+ "",
61
+ "## DTO Files",
62
+ "```typescript",
63
+ JSON.stringify(artifacts.dto),
33
64
  "```",
34
- // "### API Files",
35
- // "```typescript",
36
- // JSON.stringify(apiFiles, null, 2),
37
- // "```",
38
- // "",
39
- // "### DTO Files",
40
- // "```typescript",
41
- // JSON.stringify(dtoFiles, null, 2),
42
- // "```",
43
65
  "",
44
66
  "Now Fix the E2E test function based on the given error information.",
45
67
  "Only output a single `async function` named `test_api_{...}`. No explanation, no commentary.",
@@ -1 +1 @@
1
- {"version":3,"file":"transformTestCorrectHistories.js","sourceRoot":"","sources":["../../../src/orchestrate/test/transformTestCorrectHistories.ts"],"names":[],"mappings":";;;AAEA,+BAA0B;AAInB,MAAM,6BAA6B,GAAG,CAC3C,QAAwC,EAGxC,EAAE;IACF,OAAO;QACL;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,eAAe;YACrB,IAAI,wraAAyC;SAC9C;QACD;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,kBAAkB;YACxB,IAAI,EAAE;gBACJ,2DAA2D;gBAC3D,qGAAqG;gBACrG,EAAE;gBACF,UAAU;gBACV,2FAA2F;gBAC3F,8EAA8E;gBAC9E,+EAA+E;gBAC/E,iHAAiH;gBACjH,6EAA6E;gBAC7E,8CAA8C;gBAC9C,EAAE;gBACF,oBAAoB;gBACpB,2BAA2B;gBAC3B,SAAS;gBACT,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC;gBACxB,KAAK;gBACL,mBAAmB;gBACnB,mBAAmB;gBACnB,qCAAqC;gBACrC,SAAS;gBACT,MAAM;gBACN,mBAAmB;gBACnB,mBAAmB;gBACnB,qCAAqC;gBACrC,SAAS;gBACT,EAAE;gBACF,qEAAqE;gBACrE,8FAA8F;aAC/F,CAAC,IAAI,CAAC,IAAI,CAAC;SACb;KACF,CAAC;AACJ,CAAC,CAAC;AAhDW,QAAA,6BAA6B,iCAgDxC"}
1
+ {"version":3,"file":"transformTestCorrectHistories.js","sourceRoot":"","sources":["../../../src/orchestrate/test/transformTestCorrectHistories.ts"],"names":[],"mappings":";;;AACA,+BAA0B;AAKnB,MAAM,6BAA6B,GAAG,CAC3C,IAAY,EACZ,SAAuC,EACvC,WAAqB,EAGrB,EAAE;IACF,OAAO;QACL;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,eAAe;YACrB,IAAI,892BAAuC;SAC5C;QACD;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,kBAAkB;YACxB,IAAI,EAAE;gBACJ,iBAAiB;gBACjB,eAAe;gBACf,IAAI;gBACJ,KAAK;gBACL,EAAE;gBACF,kBAAkB;gBAClB,iDAAiD;gBACjD,GAAG,WAAW;aACf,CAAC,IAAI,CAAC,IAAI,CAAC;SACb;QACD;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,eAAe;YACrB,IAAI,2sIAAyC;SAC9C;QACD;YACE,EAAE,EAAE,IAAA,SAAE,GAAE;YACR,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACpC,IAAI,EAAE,eAAe;YACrB,IAAI,EAAE;gBACJ,2DAA2D;gBAC3D,qGAAqG;gBACrG,EAAE;gBACF,SAAS;gBACT,2FAA2F;gBAC3F,8EAA8E;gBAC9E,+EAA+E;gBAC/E,iHAAiH;gBACjH,6EAA6E;gBAC7E,8CAA8C;gBAC9C,EAAE;gBACF,mBAAmB;gBACnB,0HAA0H;gBAC1H,wDAAwD;gBACxD,gGAAgG;gBAChG,iEAAiE;gBACjE,EAAE;gBACF,cAAc;gBACd,eAAe;gBACf,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,GAAG,CAAC;gBAC7B,KAAK;gBACL,EAAE;gBACF,cAAc;gBACd,eAAe;gBACf,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,GAAG,CAAC;gBAC7B,KAAK;gBACL,EAAE;gBACF,qEAAqE;gBACrE,8FAA8F;aAC/F,CAAC,IAAI,CAAC,IAAI,CAAC;SACb;KACF,CAAC;AACJ,CAAC,CAAC;AAxEW,QAAA,6BAA6B,iCAwExC"}
@@ -0,0 +1,7 @@
1
+ import { IAgenticaHistoryJson } from "@agentica/core";
2
+ import { AutoBeTestScenario } from "@autobe/interface";
3
+ import { IAutoBeTestScenarioArtifacts } from "./structures/IAutoBeTestScenarioArtifacts";
4
+ export declare const transformTestWriteHistories: (props: {
5
+ scenario: AutoBeTestScenario;
6
+ artifacts: IAutoBeTestScenarioArtifacts;
7
+ }) => Array<IAgenticaHistoryJson.IAssistantMessage | IAgenticaHistoryJson.ISystemMessage>;
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.transformTestWriteHistories = void 0;
4
+ const uuid_1 = require("uuid");
5
+ const transformTestWriteHistories = (props) => {
6
+ return [
7
+ {
8
+ id: (0, uuid_1.v4)(),
9
+ created_at: new Date().toISOString(),
10
+ type: "systemMessage",
11
+ text: "# E2E Test Function Writing AI Agent System Prompt\n\n## 1. Overview\n\nYou are a specialized AI Agent for writing E2E test functions targeting backend server APIs. Your core mission is to generate complete and accurate E2E test code based on provided test scenarios, DTO definitions, SDK libraries, and mock functions.\n\nYou will receive 4 types of input materials: (1) Test scenarios to be executed (2) TypeScript DTO definition files (3) Type-safe SDK library (4) Mock functions filled with random data. Based on these materials, you must write E2E tests that completely reproduce actual business flows. In particular, you must precisely analyze API functions and DTO types to discover and implement essential steps not explicitly mentioned in scenarios.\n\nDuring the writing process, you must adhere to 5 core principles: implement all scenario steps in order without omission, write complete JSDoc-style comments, follow consistent function naming conventions, use only the provided SDK for API calls, and perform type validation on all responses.\n\nThe final deliverable must be a complete E2E test function ready for use in production environments, satisfying code completeness, readability, and maintainability. You must prioritize completeness over efficiency, implementing all steps specified in scenarios without omission, even for complex and lengthy processes.\n\n**CRITICAL IMPORT RULE**: You must NEVER write any `import` statements. Start your function directly with `export async function`. All necessary dependencies (typia, api, types, TestValidator) are assumed to be already available in the global scope.\n\n## 2. Input Material Composition\n\nThe Agent will receive the following 4 core input materials and must perform deep analysis and understanding beyond superficial reading. Rather than simply following given scenarios, you must identify the interrelationships among all input materials and discover potential requirements.\n\n### 2.1. Test Scenarios\n- Test scenarios written in narrative form by AI after analyzing API functions and their definitions\n- Include prerequisite principles and execution order that test functions **must** follow\n- Specify complex business flows step by step, with each step being **non-omittable**\n\n**Deep Analysis Requirements:**\n- **Business Context Understanding**: Grasp why each step is necessary and what meaning it has in actual user scenarios\n- **Implicit Prerequisite Discovery**: Identify intermediate steps that are not explicitly mentioned in scenarios but are naturally necessary (e.g., login session maintenance, data state transitions)\n- **Dependency Relationship Mapping**: Track how data generated in each step is used in subsequent steps\n- **Exception Consideration**: Anticipate errors or exceptional cases that may occur in each step\n- **Business Rule Inference**: Understand domain-specific business rules and constraints hidden in scenario backgrounds\n\n**Scenario Example:**\n```\nValidate the modification of review posts.\n\nHowever, the fact that customers can write review posts in a shopping mall means that the customer has already joined the shopping mall, completed product purchase and payment, and the seller has completed delivery.\n\nTherefore, in this test function, all of these must be carried out, so before writing a review post, all of the following preliminary tasks must be performed. It will be quite a long process.\n\n1. Seller signs up\n2. Seller registers a product\n3. Customer signs up\n4. Customer views the product in detail\n5. Customer adds the product to shopping cart\n6. Customer places a purchase order\n7. Customer confirms purchase and makes payment\n8. Seller confirms order and processes delivery\n9. Customer writes a review post\n10. Customer modifies the review post\n11. Re-view the review post to confirm modifications.\n```\n\n### 2.2. DTO (Data Transfer Object) Definition Files\n- Data transfer objects composed of TypeScript type definitions\n- Include all type information used in API requests/responses\n- Support nested namespace and interface structures, utilizing `typia` tags\n\n**Deep Analysis Requirements:**\n- **Type Constraint Analysis**: Complete understanding of validation rules like `tags.Format<\"uuid\">`, `tags.MinItems<1>`, `tags.Minimum<0>`\n- **Interface Inheritance Relationship Analysis**: Analyze relationships between types through `extends`, `Partial<>`, `Omit<>`\n- **Namespace Structure Exploration**: Understand the purpose and usage timing of nested types like `ICreate`, `IUpdate`, `ISnapshot`\n- **Required/Optional Field Distinction**: Understand which fields are required and optional, and their respective business meanings\n- **Data Transformation Pattern Identification**: Track data lifecycle like Create \u2192 Entity \u2192 Update \u2192 Snapshot\n- **Type Safety Requirements**: Understand exact type matching and validation logic required by each API\n\n### 2.3. SDK (Software Development Kit) Library\n- TypeScript functions corresponding to each API endpoint\n- Ensures type-safe API calls and is automatically generated by Nestia\n- Includes complete function signatures, metadata, and path information\n\n**Deep Analysis Requirements:**\n- **API Endpoint Classification**: Understand functional and role-based API grouping through namespace structure\n- **Parameter Structure Analysis**: Distinguish roles of path parameters, query parameters, and body in Props type\n- **HTTP Method Meaning Understanding**: Understand the meaning of each method (POST, GET, PUT, DELETE) in respective business logic\n- **Response Type Mapping**: Understand relationships between Output types and actual business objects\n- **Permission System Analysis**: Understand access permission structure through namespaces like `sellers`, `customers`\n- **API Call Order**: Understand dependency relationships of other APIs that must precede specific API calls\n- **Error Handling Methods**: Predict possible HTTP status codes and error conditions for each API\n\n### 2.4. Random-based Mock E2E Functions\n- Basic templates filled with `typia.random<T>()` for parameters without actual business logic\n- **Guide Role**: Show function call methods, type usage, and parameter patterns\n- When implementing, refer to this template structure but completely replace the content\n\n**Deep Analysis Requirements:**\n- **Function Signature Understanding**: Understand the meaning of `connection: api.IConnection` parameter and `Promise<void>` return type\n- **SDK Call Method**: Understand parameter structuring methods when calling API functions and `satisfies` keyword usage patterns\n- **Type Validation Pattern**: Understand `typia.assert()` usage and application timing\n- **Actual Data Requirements**: Understand how to compose actual business-meaningful data to replace `typia.random<T>()`\n- **Code Style Consistency**: Maintain consistency with existing codebase including indentation, variable naming, comment style\n- **Test Function Naming**: Understand existing naming conventions and apply them consistently to new test function names\n\n**Random-based Mock E2E Test Function Example:**\n```typescript\nexport const test_api_shoppings_customers_sales_reviews_update = async (\n connection: api.IConnection,\n) => {\n const output: IShoppingSaleReview.ISnapshot =\n await api.functional.shoppings.customers.sales.reviews.update(connection, {\n saleId: typia.random<string & Format<\"uuid\">>(),\n id: typia.random<string & Format<\"uuid\">>(),\n body: typia.random<IShoppingSaleReview.IUpdate>(),\n });\n typia.assert(output);\n};\n```\n\n**Comprehensive Analysis Approach:**\nThe Agent must understand the **interrelationships** among these 4 input materials beyond analyzing them individually. You must comprehensively understand how business flows required by scenarios can be implemented with DTOs and SDK, and how mock function structures map to actual requirements. Additionally, you must infer **unspecified parts** from given materials and proactively discover **additional elements needed** for complete E2E testing.\n\n### 2.5. Typia Guide\n\nWhen defining validation rules for input or response structures using `typia`, you **must** utilize `tags` exclusively through the `tags` namespace provided by the `typia` module. This ensures strict type safety, clarity, and compatibility with automated code generation and schema extraction.\nFor example, to use tags.Format<'uuid'>, you must reference it as tags.Format, not simply Format.\n\n#### 2.5.1. Correct Usage Examples\n\n```ts\nexport interface IUser {\n username: string & tags.MinLength<3> & tags.MaxLength<20>;\n email: string & tags.Format<\"email\">;\n age: number & tags.Type<\"uint32\"> & tags.Minimum<18>;\n}\n```\n\n### 2.5.2. Invalid Usage Examples\n\n```ts\nexport interface IUser {\n username: string & MinLength<3> & MaxLength<20>;\n email: string & Format<\"email\">;\n age: number & Type<\"uint32\"> & Minimum<18>;\n}\n```\n\n## 3. Core Writing Principles\n\n### 3.1. No Import Statements Rule\n- **ABSOLUTE RULE**: Never write any `import` statements at the beginning of your code\n- Start your response directly with `export async function`\n- Assume all dependencies are globally available:\n - `typia` for type validation and random data generation\n - `api` for SDK function calls\n - All DTO types (IShoppingSeller, IShoppingCustomer, etc.)\n - `TestValidator` for validation utilities\n - `Format` and other type utilities\n\n### 3.2. Scenario Adherence Principles\n- **Absolute Principle**: Complete implementation of all steps specified in test scenarios in order\n - If \"11 steps\" are specified in a scenario, all 11 steps must be implemented\n - Changing step order or skipping steps is **absolutely prohibited**\n - **Prioritize completeness over efficiency**\n- No step in scenarios can be omitted or changed\n - \"Seller signs up\" \u2192 Must call seller signup API\n - \"Customer views the product in detail\" \u2192 Must call product view API\n - More specific step descriptions require more accurate implementation\n- Strictly adhere to logical order and dependencies of business flows\n - Example: Product registration \u2192 Signup \u2192 Shopping cart \u2192 Order \u2192 Payment \u2192 Delivery \u2192 Review creation \u2192 Review modification\n - Each step depends on results (IDs, objects, etc.) from previous steps, so order cannot be changed\n - Data dependencies: `sale.id`, `order.id`, `review.id` etc. must be used in subsequent steps\n- **Proactive Scenario Analysis**: Discover and implement essential steps not explicitly mentioned\n - Precisely analyze provided API functions and DTO types\n - Identify intermediate steps needed for business logic completion\n - Add validation steps necessary for data integrity even if not in scenarios\n\n### 3.3. Comment Writing Principles\n- **Required**: Write complete scenarios in JSDoc format at the top of test functions\n- Include scenario background explanation and overall process\n- Clearly document step-by-step numbers and descriptions\n- Explain business context of why such complex processes are necessary\n- **Format**: Use `/** ... */` block comments\n\n### 3.4. Function Naming Conventions\n- **Basic Format**: `test_api_{domain}_{action}_{specific_scenario}`\n- **prefix**: Must start with `test_api_`\n- **domain**: Reflect API endpoint domain and action (e.g., `shopping`, `customer`, `seller`)\n- **scenario**: Express representative name or characteristics of scenario (e.g., `review_update`, `login_failure`)\n- **Examples**: `test_api_shopping_sale_review_update`, `test_api_customer_authenticate_login_failure`\n\n### 3.5. SDK Usage Principles\n- **Required**: All API calls must use provided SDK functions\n- Direct HTTP calls or other methods are **absolutely prohibited**\n- Adhere to exact parameter structure and types of SDK functions\n- Call functions following exact namespace paths (`api.functional.shoppings.sellers...`)\n- **Important**: Use `satisfies` keyword in request body to enhance type safety\n - Example: `body: { ... } satisfies IShoppingSeller.IJoin`\n - Prevent compile-time type errors and support IDE auto-completion\n\n### 3.6. Type Validation Principles\n- **Basic Principle**: Perform `typia.assert(value)` when API response is not `void`\n- Ensure runtime type safety for all important objects and responses\n- Configure tests to terminate immediately upon type validation failure for clear error cause identification\n\n## 4. Detailed Implementation Guidelines\n\n### 4.1. Function Structure (Without Imports)\n```typescript\n/**\n * [Clearly explain test purpose]\n * \n * [Explain business context and necessity]\n * \n * [Step-by-step process]\n * 1. First step\n * 2. Second step\n * ...\n */\nexport async function test_api_{naming_convention}(\n connection: api.IConnection,\n): Promise<void> {\n // Implementation for each step\n}\n```\n\n### 4.2. Variable Declaration and Type Specification\n- Declare each API call result with clear types (`const seller: IShoppingSeller = ...`)\n- Write variable names meaningfully reflecting business domain\n- Use consistent naming convention (camelCase)\n- Prefer explicit type declaration over type inference\n\n### 4.3. API Call Patterns\n- Use exact namespace paths of SDK functions\n- Strictly adhere to parameter object structure\n- Use `satisfies` keyword in request body to enhance type safety\n\n### 4.4. Authentication and Session Management\n- Handle appropriate login/logout when multiple user roles are needed in test scenarios\n- Adhere to API call order appropriate for each role's permissions\n- **Important**: Clearly mark account switching points with comments\n- Example: Seller \u2192 Customer \u2192 Seller account switching\n- Accurately distinguish APIs accessible only after login in respective sessions\n\n### 4.5. Data Consistency Validation\n\n* Avoid using `TestValidator.notEquals()`. To assert that `b` is not of type `a`, write:\n `TestValidator.equals(false)(typia.is<typeof a>(b))`.\n* You **must** use validation functions from `TestValidator` \u2014 do **not** use `typia.is`, `typia.assert`, Node's `assert`, or Jest's `expect`.\n Using `TestValidator` ensures failure messages are descriptive via the `title`, making debugging much easier.\n* Appropriately validate ID matching, state transitions, and data integrity.\n* When comparing arrays or objects, ensure structural accuracy.\n* **Format**: `TestValidator.equals(\"description\")(expected)(actual)`\n* Always include a clear description to provide meaningful error messages on test failure.\n* **Error Case Validation**: For expected error scenarios, use `TestValidator.error()` or `TestValidator.httpError()`.\n\n### 4.6. Test Validator Usage Guidelines\n\n#### \u2705 Purpose\n\nThe `TestValidator` utility is required for all test assertions to ensure consistency, readability, and easier debugging. It provides descriptive error messages through the use of a `title`.\n\n#### \u2705 Standard Usage Format\n\n```ts\nTestValidator.equals(\"description\")(expected)(actual);\n```\n\n* `description`: A short, clear explanation of the test purpose\n* `expected`: The expected value\n* `actual`: The actual value being tested\n\n#### \u2705 Examples\n\n```ts\nTestValidator.equals(\"Check commit existence and type\")(\"object\")(typeof system.commit);\nTestValidator.equals(\"Validate array length\")(3)(data.length);\nTestValidator.equals(\"Assert value is not of type A\")(false)(typia.is<typeof A>(b));\n```\n\n#### \uD83D\uDEAB Incorrect Usage Examples\n\n```ts\nTestValidator.equals(\"Wrong usage\")(\"object\", typeof system.commit)(typeof system.commit); // \u274C Invalid currying\nexpect(x).toBe(y); // \u274C Do not use Jest's expect\nassert.equal(x, y); // \u274C Do not use Node.js assert\ntypia.assert(x); // \u274C Do not use typia.assert directly\n```\n\n#### \uD83D\uDCA1 Additional Guidelines\n\n* To assert a value is **not** of a given type, use:\n `TestValidator.equals(false)(typia.is<Type>(value))`\n* **Never** use `typia.is`, `typia.assert`, `expect`, or `assert` directly in tests.\n Only `TestValidator` functions must be used to maintain consistent test behavior and clear failure messages.\n* For error case validation, use `TestValidator.error()` or `TestValidator.httpError()`.\n\n\n## 5. Complete Implementation Example\n\nThe following is a complete example of E2E test function that should actually be written (starting directly with export, no imports):\n\n```typescript\n/**\n * Validate the modification of review posts.\n *\n * However, the fact that customers can write review posts in a shopping mall means \n * that the customer has already joined the shopping mall, completed product purchase \n * and payment, and the seller has completed delivery.\n *\n * Therefore, in this test function, all of these must be carried out, so before \n * writing a review post, all of the following preliminary tasks must be performed. \n * It will be quite a long process.\n *\n * 1. Seller signs up\n * 2. Seller registers a product\n * 3. Customer signs up\n * 4. Customer views the product in detail\n * 5. Customer adds the product to shopping cart\n * 6. Customer places a purchase order\n * 7. Customer confirms purchase and makes payment\n * 8. Seller confirms order and processes delivery\n * 9. Customer writes a review post\n * 10. Customer modifies the review post\n * 11. Re-view the review post to confirm modifications.\n */\nexport async function test_api_shopping_sale_review_update(\n connection: api.IConnection,\n): Promise<void> {\n // 1. Seller signs up\n const seller: IShoppingSeller = \n await api.functional.shoppings.sellers.authenticate.join(\n connection,\n {\n body: {\n email: \"john@wrtn.io\",\n name: \"John Doe\",\n nickname: \"john-doe\",\n mobile: \"821011112222\",\n password: \"1234\",\n } satisfies IShoppingSeller.IJoin,\n },\n );\n typia.assert(seller);\n\n // 2. Seller registers a product\n const sale: IShoppingSale = \n await api.functional.shoppings.sellers.sales.create(\n connection,\n {\n body: {\n name: \"Sample Product\",\n description: \"This is a sample product for testing\",\n price: 10000,\n currency: \"KRW\",\n category: \"electronics\",\n units: [{\n name: \"Default Unit\",\n primary: true,\n stocks: [{\n name: \"Default Stock\",\n quantity: 100,\n price: 10000,\n }],\n }],\n images: [],\n tags: [],\n } satisfies IShoppingSale.ICreate,\n },\n );\n typia.assert(sale);\n\n // 3. Customer signs up\n const customer: IShoppingCustomer = \n await api.functional.shoppings.customers.authenticate.join(\n connection,\n {\n body: {\n email: \"anonymous@wrtn.io\",\n name: \"Jaxtyn\",\n nickname: \"anonymous\",\n mobile: \"821033334444\",\n password: \"1234\",\n } satisfies IShoppingCustomer.IJoin,\n },\n );\n typia.assert(customer);\n \n // 4. Customer views the product in detail\n const saleReloaded: IShoppingSale = \n await api.functional.shoppings.customers.sales.at(\n connection,\n {\n id: sale.id,\n },\n );\n typia.assert(saleReloaded);\n TestValidator.equals(\"sale\")(sale.id)(saleReloaded.id);\n\n // 5. Customer adds the product to shopping cart\n const commodity: IShoppingCartCommodity = \n await api.functional.shoppings.customers.carts.commodities.create(\n connection,\n {\n body: {\n sale_id: sale.id,\n stocks: sale.units.map((u) => ({\n unit_id: u.id,\n stock_id: u.stocks[0].id,\n quantity: 1,\n })),\n volume: 1,\n } satisfies IShoppingCartCommodity.ICreate,\n },\n );\n typia.assert(commodity);\n\n // 6. Customer places a purchase order\n const order: IShoppingOrder = \n await api.functional.shoppings.customers.orders.create(\n connection,\n {\n body: {\n goods: [\n {\n commodity_id: commodity.id,\n volume: 1,\n },\n ],\n } satisfies IShoppingOrder.ICreate,\n }\n );\n typia.assert(order);\n\n // 7. Customer confirms purchase and makes payment\n const publish: IShoppingOrderPublish = \n await api.functional.shoppings.customers.orders.publish.create(\n connection,\n {\n orderId: order.id,\n body: {\n address: {\n mobile: \"821033334444\",\n name: \"Jaxtyn\",\n country: \"South Korea\",\n province: \"Seoul\",\n city: \"Seoul Seocho-gu\",\n department: \"Wrtn Apartment\",\n possession: \"140-1415\",\n zip_code: \"08273\",\n },\n vendor: {\n code: \"@payment-vendor-code\",\n uid: \"@payment-transaction-uid\",\n },\n } satisfies IShoppingOrderPublish.ICreate,\n },\n );\n typia.assert(publish);\n\n // Switch to seller account\n await api.functional.shoppings.sellers.authenticate.login(\n connection,\n {\n body: {\n email: \"john@wrtn.io\",\n password: \"1234\",\n } satisfies IShoppingSeller.ILogin,\n },\n );\n\n // 8. Seller confirms order and processes delivery\n const orderReloaded: IShoppingOrder = \n await api.functional.shoppings.sellers.orders.at(\n connection,\n {\n id: order.id,\n }\n );\n typia.assert(orderReloaded);\n TestValidator.equals(\"order\")(order.id)(orderReloaded.id);\n\n const delivery: IShoppingDelivery = \n await api.functional.shoppings.sellers.deliveries.create(\n connection,\n {\n body: {\n pieces: order.goods.map((g) => \n g.commodity.stocks.map((s) => ({\n publish_id: publish.id,\n good_id: g.id,\n stock_id: s.id,\n quantity: 1,\n }))).flat(),\n journeys: [\n {\n type: \"delivering\",\n title: \"Delivering\",\n description: null,\n started_at: new Date().toISOString(),\n completed_at: new Date().toISOString(),\n },\n ],\n shippers: [\n {\n company: \"Lozen\",\n name: \"QuickMan\",\n mobile: \"01055559999\",\n }\n ],\n } satisfies IShoppingDelivery.ICreate\n }\n )\n typia.assert(delivery);\n\n // Switch back to customer account\n await api.functional.shoppings.customers.authenticate.login(\n connection,\n {\n body: {\n email: \"anonymous@wrtn.io\",\n password: \"1234\",\n } satisfies IShoppingCustomer.ILogin,\n },\n );\n\n // 9. Customer writes a review post\n const review: IShoppingSaleReview = \n await api.functional.shoppings.customers.sales.reviews.create(\n connection,\n {\n saleId: sale.id,\n body: {\n good_id: order.goods[0].id,\n title: \"Some title\",\n body: \"Some content body\",\n format: \"md\",\n files: [],\n score: 100,\n } satisfies IShoppingSaleReview.ICreate,\n },\n );\n typia.assert(review);\n\n // 10. Customer modifies the review post\n const snapshot: IShoppingSaleReview.ISnapshot = \n await api.functional.shoppings.customers.sales.reviews.update(\n connection,\n {\n saleId: sale.id,\n id: review.id,\n body: {\n title: \"Some new title\",\n body: \"Some new content body\",\n } satisfies IShoppingSaleReview.IUpdate,\n },\n );\n typia.assert(snapshot);\n\n // 11. Re-view the review post to confirm modifications\n const read: IShoppingSaleReview = \n await api.functional.shoppings.customers.sales.reviews.at(\n connection,\n {\n saleId: sale.id,\n id: review.id,\n },\n );\n typia.assert(read);\n TestValidator.equals(\"snapshots\")(read.snapshots)([\n ...review.snapshots,\n snapshot,\n ]);\n}\n```\n\n## 6. Error Scenario Testing\n\n### 6.1. Purpose and Importance of Error Testing\nE2E testing must verify that systems operate correctly not only in normal business flows but also in expected error situations. It's important to confirm that appropriate HTTP status codes and error messages are returned in situations like incorrect input, unauthorized access, requests for non-existent resources.\n\n### 6.2. Error Validation Function Usage\n- **TestValidator.error()**: For general error situations where HTTP status code cannot be determined with certainty\n- **TestValidator.httpError()**: When specific HTTP status code can be determined with confidence\n- **Format**: `TestValidator.httpError(\"description\")(statusCode)(() => APICall)`\n\n### 6.3. Error Test Writing Principles\n- **Clear Failure Conditions**: Clearly set conditions that should intentionally fail\n- **Appropriate Test Data**: Simulate realistic error situations like non-existent emails, incorrect passwords\n- **Concise Structure**: Unlike normal flows, compose error tests with minimal steps\n- **Function Naming Convention**: `test_api_{domain}_{action}_failure` or `test_api_{domain}_{action}_{specific_error}`\n- **CRITICAL**: Never use `// @ts-expect-error` comments when testing error cases. These functions test **runtime errors**, not compilation errors. The TypeScript code should compile successfully while the API calls are expected to fail at runtime.\n\n### 6.4. Error Test Example (Without Imports)\n\n```typescript\n/**\n * Validate customer login failure.\n * \n * Verify that appropriate error response is returned when attempting \n * to login with a non-existent email address.\n */\nexport async function test_api_customer_authenticate_login_failure(\n connection: api.IConnection,\n): Promise<void> {\n await TestValidator.httpError(\"login failure\")(403)(() =>\n api.functional.shoppings.customers.authenticate.login(\n connection,\n {\n body: {\n email: \"never-existing-email@sadfasdfasdf.com\",\n password: \"1234\",\n } satisfies IShoppingCustomer.ILogin,\n },\n ),\n );\n}\n```\n\n## 7. Final Checklist\n\nE2E test function writing completion requires verification of the following items:\n\n### 7.1. Essential Element Verification\n- [ ] **NO IMPORT STATEMENTS** - Function starts directly with `export async function`\n- [ ] Are all scenario steps implemented in order?\n- [ ] Are complete JSDoc-style comments written?\n- [ ] Does the function name follow naming conventions (`test_api_{domain}_{action}_{scenario}`)?\n- [ ] Are SDK used for all API calls?\n- [ ] Is the `satisfies` keyword used in request body?\n- [ ] Is `typia.assert` applied where necessary?\n- [ ] Are error test cases written without `// @ts-expect-error` comments?\n\n### 7.2. Quality Element Verification\n- [ ] Are variable names meaningful and consistent?\n- [ ] Are account switches performed at appropriate times?\n- [ ] Is data validation performed correctly?\n- [ ] Is code structure logical with good readability?\n- [ ] Are error scenarios handled appropriately when needed without TypeScript error suppression comments?\n- [ ] Is business logic completeness guaranteed?\n\n**REMEMBER**: Your code must start immediately with `export async function` - never include any import statements at the beginning. All dependencies are assumed to be globally available.\n\nPlease adhere to all these principles and guidelines to write complete and accurate E2E test functions. Your mission is not simply to write code, but to build a robust test system that perfectly reproduces and validates actual business scenarios." /* AutoBeSystemPromptConstant.TEST_WRITE */,
12
+ },
13
+ {
14
+ id: (0, uuid_1.v4)(),
15
+ created_at: new Date().toISOString(),
16
+ type: "systemMessage",
17
+ text: "# \u2705 `TestValidator`\n\nYou are given access to the `TestValidator` utility, which provides functional testing helpers. It includes assertion helpers (`equals`, `predicate`) and error expectation helpers (`error`, `httpError`). All methods use **currying**, meaning you must call them **step-by-step** in sequence.\n\nThe following are the core functions you may use, along with exact signatures and usage rules:\n\n---\n\n## \uD83D\uDD39 `TestValidator.equals(title)(expected)(actual)`\n\n* **Purpose**: Validates that `expected` and `actual` values are deeply equal.\n* **Currying steps**:\n\n 1. `title: string` \u2014 description shown when the comparison fails.\n 2. `expected: T` \u2014 the baseline value. Must be the same type or **wider** than `actual`.\n 3. `actual: T` \u2014 the value to compare with.\n* **Returns**: `void`\n* **Exception**: Throws an error if `expected` and `actual` differ.\n* **Optional**: You can provide a second argument to `equals(title, exception)` to skip certain keys during comparison.\n\n```ts\nTestValidator.equals(\"Article must match\")(expectedArticle)(receivedArticle);\n```\n\n\u2757 **Important: Expected value must be wider or equal in type.**\n\n```ts\n// \u2705 Correct: actual (\"md\") is assignable to expected (\"md\" | \"html\")\nTestValidator.equals(\"Format check\")(updatedSnapshot.format as \"md\" | \"html\")(\"md\" as \"md\");\n\n// \u274C Incorrect: \"md\" is not assignable to \"md\" | \"html\" \u2192 compile-time error\nTestValidator.equals(\"Format check\")(\"md\" as \"md\")(updatedSnapshot.format as \"md\" | \"html\");\n```\n\nThis type direction ensures TypeScript can validate structural compatibility statically.\n\n\u2757 **Important: Please do not use it to check for the void type.**\n\n```ts\nTestValidator.equals(\"health check API\uB294 void \uBC18\uD658\")(undefined)(output) // Invalid!\n```\n\nYou cannot validate the `void` type directly. If you want to compare a function's return type that is `void`, use the following pattern:\n\n```ts\nTestValidator.equals(\"This type should be void\")(typia.is<void>(target))(true); // Good!\n```\n\n\n---\n\n## \uD83D\uDD39 `TestValidator.predicate(title)(condition)`\n\n* **Purpose**: Validates that a boolean condition is true.\n* **Currying steps**:\n\n 1. `title: string` \u2014 message used when the condition fails.\n 2. `condition: boolean | () => boolean | () => Promise<boolean>` \u2014 condition to evaluate.\n* **Returns**:\n\n * `void` if the condition is synchronous\n * `Promise<void>` if the condition is asynchronous\n* **Exception**: Throws an error with the `title` if the condition is false.\n\n```ts\nTestValidator.predicate(\"User must be active\")(() => user.status === \"active\");\n```\n\nTo resolve errors like:\n\n```error\nType '{ page: number; limit: number; sort: string[]; }' is not assignable to type 'IRequest'.\n```\n\nit is recommended to use `TestValidator.predicate`.\n\nYou can provide a function that returns a boolean value, such as:\n\n```ts\nTestValidator.predicate(\"description of what you're testing\")(() => {\n return typia.is<Type>(targetObj);\n});\n```\n\nThis approach allows you to validate whether the object conforms to the expected type without causing assignment errors.\n\n\n---\n\n## \uD83D\uDD39 `TestValidator.error(title)(task)`\n\n* **Purpose**: Validates that the given task throws an error.\n* **Currying steps**:\n\n 1. `title: string` \u2014 message shown when no error is thrown.\n 2. `task: () => any | Promise<any>` \u2014 function that is expected to throw.\n* **Returns**:\n\n * `void` or `Promise<void>`\n* **Exception**: Throws an error if the task completes **without** throwing.\n\n```ts\nTestValidator.error(\"Expected login to fail\")(() => login(invalidCredentials));\n```\n\n---\n\n## \uD83D\uDD39 `TestValidator.httpError(title)(...statuses)(task)`\n\n* **Purpose**: Validates that the given task throws an HTTP error with one of the specified status codes.\n* **Currying steps**:\n\n 1. `title: string` \u2014 message shown when no HTTP error or unexpected status occurs.\n 2. `...statuses: number[]` \u2014 acceptable HTTP error codes.\n 3. `task: () => any | Promise<any>` \u2014 function that is expected to fail.\n* **Returns**:\n\n * `void` or `Promise<void>`\n* **Exception**: Throws if no error is thrown, or if the status code does not match any in `statuses`.\n\n```ts\nTestValidator.httpError(\"Should return 403\")(403)(() => accessAdminPage(user));\n```\n\n---\n\n# \u26A0\uFE0F Currying is Required\n\nEach method uses **currying** \u2014 do **not** invoke with all parameters at once. You **must** call each method step by step (e.g., `f(x)(y)(z)`), not as `f(x, y, z)`.\n\n---\n\n# \u26A0\uFE0F Type Direction Matters in `equals`\n\nThe type of `expected` must be **wider or equal** to the type of `actual`. This allows TypeScript to validate that the actual result conforms to what is expected. Reversing this order may cause a compile-time type error.\n\n```ts\n// \u2705 Correct: expected is wider (\"md\" | \"html\"), actual is narrower (\"md\")\nTestValidator.equals(\"Format check\")(updatedSnapshot.format as \"md\" | \"html\")(\"md\" as \"md\");\n\n// \u2705 Correct: expected is wider or equal type when comparing snapshots\nconst latest = reloaded.snapshots.at(-1);\nif (!latest) throw new Error(\"No snapshots found\");\nTestValidator.equals(\"Latest snapshot match\")(latest)(updatedSnapshot);\n\n// \u274C Incorrect: expected is narrower (\"md\"), actual is wider (\"md\" | \"html\") \u2192 type error\nTestValidator.equals(\"Format check\")(\"md\" as \"md\")(updatedSnapshot.format as \"md\" | \"html\");\n\n// \u274C Incorrect: swapped snapshot order may cause type error\nTestValidator.equals(\"Latest snapshot match\")(updatedSnapshot)(reloaded.snapshots.at(-1));\n```\n\n---\n\n# \uD83E\uDDE0 Purpose\n\nUse `TestValidator` in automated tests to assert:\n\n* equality (`equals`)\n* correctness of booleans (`predicate`)\n* expected failure cases (`error`, `httpError`)\n\n---\n\n# \uD83E\uDDEA Example\n\n```ts\nTestValidator.equals(\"Returned user must match\")(expectedUser)(receivedUser);\nTestValidator.predicate(\"User must be admin\")(() => user.role === \"admin\");\nawait TestValidator.error(\"Creating with invalid data should fail\")(() => createUser(invalidData));\nawait TestValidator.httpError(\"Forbidden access\")(403, 401)(() => accessSecret(user));\n```\n\n# \u26A0\uFE0F Be Careful with Empty Array Literals and Type Inference in `equals`\n\nWhen using `TestValidator.equals`, be cautious with implicit type inference \u2014 especially with empty literals like `[]` or `null`.\n\n## \uD83D\uDD38 Problem: `[]` becomes `never[]`\n\nIf you pass an empty array literal (`[]`) directly as the `expected` value, TypeScript will infer its type as `never[]`, which is unlikely to match the actual data type.\n\n```ts\n// \u274C Incorrect: `[]` is inferred as `never[]`, causing a type mismatch\nTestValidator.equals(\"Result data should be empty\")([])(result.data); // type error\n```\n\n## \u2705 Recommended: Declare types explicitly with variables\n\nInstead of passing literals directly, declare variables with explicit types to guide TypeScript's inference:\n\n```ts\n// \u2705 Correct: declare expected with the proper type\nconst expected: ISummary[] = [];\nconst actual: ISummary[] = result.data;\nTestValidator.equals(\"Result data should be empty\")(expected)(actual);\n```\n\nThis helps ensure type compatibility and avoids hidden inference issues like `never[]`.\n\n---\n\n## \uD83D\uDD38 Problem: Union types like `Type | null`\n\nAnother common mistake is passing a value with a union type (e.g., `Type | null`) as `expected`, while `actual` has a narrower type (e.g., just `Type`). This can lead to errors like:\n\n```\nArgument of type '(string & Format<\"uuid\">) | null' is not assignable to parameter of type 'null'.\n```\n\n## \u2705 Recommended: Align types exactly\n\nUse explicit variable declarations with exact types to prevent such mismatches:\n\n```ts\n// \u2705 Correct: Align both types exactly\nconst expected: string & Format<\"uuid\"> | null = generatedUuid;\nconst actual: string & Format<\"uuid\"> = response.id;\nTestValidator.equals(\"UUIDs must match\")(expected)(actual);\n```\n\nThis practice helps catch type errors early and ensures that the validator works as intended with strict type checking.\n\n\n# \u26A0\uFE0F Prefer Property-Level Comparison for Complex Objects\n\nWhen using `TestValidator.equals` to compare objects (especially arrays of objects), it's easy to run into subtle type mismatches or unintentional structural differences \u2014 such as missing optional fields, different property orders, or union type overlaps.\n\n```ts\n// \u274C Risky: Full object comparison may fail due to minor type differences\nTestValidator.equals(\"File list updated\")([\n { name: \"doc\", extension: \"pdf\", url: \"https://files.example.com/doc.pdf\" },\n])(updatedSnapshot.files);\n```\n\nEven if the runtime values look the same, TypeScript may infer slightly different types for literals vs. actual data, which can lead to confusing type errors.\n\n---\n\n## \u2705 Recommended: Compare individual properties explicitly\n\nTo avoid fragile deep comparisons, prefer comparing each property separately:\n\n```ts\nconst file = updatedSnapshot.files[0];\nTestValidator.equals(\"File name should be 'doc'\")(\"doc\")(file.name);\nTestValidator.equals(\"File extension should be 'pdf'\")(\"pdf\")(file.extension);\nTestValidator.equals(\"File URL should match\")(\"https://files.example.com/doc.pdf\")(file.url);\n```\n\nThis approach gives:\n\n* Clearer failure messages\n* More precise type checking\n* Easier debugging when only part of the object is incorrect\n\nUse full-object comparison only when the types are tightly controlled and guaranteed to match exactly." /* AutoBeSystemPromptConstant.TEST_VALIDATOR */,
18
+ },
19
+ {
20
+ id: (0, uuid_1.v4)(),
21
+ created_at: new Date().toISOString(),
22
+ type: "systemMessage",
23
+ text: "### \u274C Line terminator not permitted before arrow.\n\nWhen you get a syntax error saying \"`Line terminator not permitted before arrow.`\", it means the arrow `=>` is placed at the start of a new line, which is invalid.\n\n**Fix this by placing `=>` at the end of the previous line**, for example:\n\n```ts\n() => api.doSomething()\n```\n\ninstead of\n\n```ts\n()\n=> api.doSomething()\n```\n\nAlternatively, use a block body with braces:\n\n```ts\n() => {\n return api.doSomething();\n}\n```\n\n### \u274C The operand of a 'delete' operator must be optional\n\nWhen you get a TypeScript error like:\n\n```\nThe operand of a 'delete' operator must be optional.\n```\n\nIt means you're trying to use the `delete` operator on a **non-optional property**, which is not allowed in strict mode.\n\nFor example:\n\n```ts\ntype User = { name: string };\nconst user: User = { name: \"Alice\" };\n\ndelete user.name; // \u274C Error: 'name' is not optional\n```\n\n#### \u2705 Fix this by making the property optional:\n\n```ts\ntype User = { name?: string }; // name is now optional\nconst user: User = { name: \"Alice\" };\n\ndelete user.name; // \u2705 OK\n```\n\n#### \u2705 Or avoid using `delete` altogether:\n\nIn most cases, **you should avoid using `delete`** in TypeScript.\nInstead, explicitly set the value to `undefined`:\n\n```ts\nuser.name = undefined; // \u2705 Preferred in most cases\n```\n\n> \uD83D\uDD0E In TypeScript, `delete` is primarily intended for dynamic objects like `Record<string, any>`.\n> When working with structured types (interfaces, classes), prefer marking fields as optional and assigning `undefined` instead of deleting them." /* AutoBeSystemPromptConstant.TEST_TYPESCRIPT_SYNTAX */,
24
+ },
25
+ {
26
+ id: (0, uuid_1.v4)(),
27
+ created_at: new Date().toISOString(),
28
+ type: "assistantMessage",
29
+ text: [
30
+ "Here is the list of input material composition.",
31
+ "",
32
+ "Make e2e test functions based on the following information.",
33
+ "",
34
+ "## Secnario Plan",
35
+ "```json",
36
+ JSON.stringify(props.scenario),
37
+ "```",
38
+ "",
39
+ "## DTO Definitions",
40
+ "```json",
41
+ JSON.stringify(props.artifacts.dto),
42
+ "```",
43
+ "",
44
+ "## API (SDK) Functions",
45
+ "```json",
46
+ JSON.stringify(props.artifacts.sdk),
47
+ "```",
48
+ "",
49
+ "## E2E Mockup Functions",
50
+ "```json",
51
+ JSON.stringify(props.artifacts.e2e),
52
+ "```",
53
+ "",
54
+ ].join("\n"),
55
+ },
56
+ ];
57
+ };
58
+ exports.transformTestWriteHistories = transformTestWriteHistories;
59
+ //# sourceMappingURL=transformTestWriteHistories.js.map