A Pre-Commit AI Review Workflow That Catches What Local Tests Miss
Before submitting code, you usually do a few things:
- Review the modified code.
- Run the project and tests.
- Check for any missing features.
- Wait for a colleague to do a Code Review.
Now, we can add one more step:
Let AI check it first, then submit the code.
AI can help us discover problems that are easy to overlook, such as logic errors, security risks, boundary conditions, and code style issues.
But note:
AI code review can only serve as an aid; it cannot replace manual review, automated testing, or security audits.
1. Why code review is needed before submission
Code that runs does not mean it is problem-free.
For example, the following issues may not cause errors when the project starts:
- User input is not validated.
- Passwords are stored in plain text.
- SQL statements have injection risks.
- Ordinary users can submit an admin role.
- Exception information is returned directly to the frontend.
- Empty data and duplicate data are not handled.
- Code changes affect existing functionality.
- Files unrelated to the requirements are submitted.
Some of these are functional problems, some are security problems, and some increase future maintenance costs.
If they are only discovered after going live, the cost of fixing them is usually higher.
Therefore, it is necessary to perform a check before submitting code.
2. What AI code review can check
1. Obvious errors and logic issues
AI can help check:
- Whether conditional judgments are correct.
- Whether variables might be null.
- Whether return results meet requirements.
- Whether asynchronous code is handled correctly.
- Whether there is duplicate execution.
- Whether error handling is missing.
- Whether the modified code affects original logic.
For example, a requirement says "only logged-in users can delete data," but the code does not verify login status—this is an obvious logic problem.
2. Security risks
Security issues are usually not easy to find through ordinary testing.
AI can assist in checking:
- SQL injection.
- XSS injection.
- Unauthorized access.
- Sensitive information leakage.
- Plain-text password storage.
- Unfiltered user input.
- File upload risks.
- Incomplete permission checks.
- Keys, tokens, or cookies being committed.
However, for security-related code, you cannot rely solely on AI's judgment; manual confirmation should also be combined with the team's security standards.
3. Code style and maintainability
AI can also help check whether code is easy to read and maintain:
- Whether variable names are clear.
- Whether functions take on too many responsibilities.
- Whether there is duplicate code.
- Whether overly complex writing is used.
- Whether it is consistent with the project's existing style.
- Whether necessary comments are missing.
- Whether unrelated files have been modified.
Code style issues usually do not cause immediate failures, but they affect subsequent development efficiency.
4. Boundary conditions and exception handling
Many problems occur outside the normal flow.
For example:
- What if the username is empty?
- What if the password length does not meet requirements?
- What if the parameter type is wrong?
- What if the data does not exist?
- What if the data is duplicated?
- What if the database connection fails?
- What if the user clicks repeatedly?
- What if the returned data is empty?
AI is well-suited to help us supplement these easily overlooked scenarios.
3. An example of an interface that needs review
Suppose we are developing a user creation interface, with a tech stack of Node.js and Express.
The requirements are as follows:
- Users can submit a username and password.
- After successful registration, a normal user is created.
- Usernames cannot be duplicated.
- Passwords cannot be stored in plain text.
- When registration fails, internal database errors must not be returned.
Below is a version that looks runnable but has multiple problems:
app.post('/api/users', async (req, res) => {
const { username, password, role } = req.body;
const sql = `
INSERT INTO users (username, password, role)
VALUES ('${username}', '${password}', '${role}')
`;
try {
await db.query(sql);
res.json({
code: 0,
message: '创建成功'
});
} catch (error) {
res.status(500).json({
code: 500,
message: error.message
});
}
});
The problems in this code will not necessarily be exposed in local testing.
For example:
- It does not check whether username and password are empty.
- SQL is directly concatenated, which may lead to SQL injection.
- The password is stored directly without encryption or hashing.
roleis submitted by the user, so a user could set themselves as admin.- Database error information is returned directly to the frontend.
- Duplicate username cases are not handled.
Next, you can hand the requirements, code, and constraints to AI for review.
4. How to provide AI with code review context
Don't just send a sentence like:
Help me see if there are any problems with this code.
This sentence lacks project background, making it hard for AI to judge what is "correct."
You can use the following prompt:
Please help me review the following code change.
Project background:
This is a Node.js + Express user registration interface.
Users can submit a username and password, but can only create normal users.
After successful registration, user information is saved.
Business requirements:
1. Username cannot be empty, length 3 to 20 characters.
2. Password cannot be empty, length no less than 8 characters.
3. Password cannot be stored in plain text.
4. Users cannot modify their own role through request parameters.
5. Return a clear business prompt when the username is duplicated.
6. Do not return internal database errors to the frontend.
Please review from the following four aspects:
1. Functionality and logic errors
2. Security risks
3. Boundary conditions and exception handling
4. Code style and maintainability
Please strictly output in the following format:
- Problem location
- Severity: High, Medium, Low
- Problem description
- Possible impact
- Modification suggestion
- Suggested verification method
Requirements:
- First only list the problems, do not directly rewrite the entire file.
- Do not speculate on features that do not exist in the project.
- If you cannot determine something, clearly state what additional information is needed.
Code to be reviewed:
[Paste code]
This prompt has several key points:
- It explains the project background.
- It explains the real business rules.
- It specifies the scope of the check.
- It requires AI to mark the problem location and severity.
- It requires outputting problems first, not directly rewriting the code.
5. How to read AI's review results
AI may list many suggestions, but not all suggestions are equally important.
We can categorize them by impact scope.
High-priority issues
These issues should be fixed first:
- SQL injection.
- Unauthorized access.
- Plain-text password storage.
- Sensitive information leakage.
- Users can escalate privileges to modify roles.
- Possible data loss.
- Core business logic errors.
For example, allowing users to submit role: "admin" via parameters is a serious permission problem.
Medium-priority issues
These issues usually need to be addressed before submission:
- Incomplete parameter validation.
- Duplicate data not handled.
- Unclear exception responses.
- Functions with too many responsibilities.
- Missing tests for key logic.
- Empty data causing page exceptions.
These problems may not immediately cause security incidents, but they affect functional stability and maintenance efficiency.
Low-priority issues
These issues can be handled according to project standards:
- Variable naming not clear enough.
- Function length somewhat long.
- Comments not complete enough.
- Format inconsistent with project standards.
- A small amount of duplicate code exists.
Low priority does not mean not handling them at all, but arranging them based on time and actual benefit.
6. Modifying code based on review results
For the previous example, the following modifications can be made:
app.post('/api/users', async (req, res) => {
const { username, password } = req.body;
if (
typeof username !== 'string' ||
username.length < 3 ||
username.length > 20
) {
return res.status(400).json({
code: 40001,
message: '用户名长度必须为 3 到 20 个字符'
});
}
if (typeof password !== 'string' || password.length < 8) {
return res.status(400).json({
code: 40002,
message: '密码长度不能少于 8 位'
});
}
try {
const passwordHash = await bcrypt.hash(password, 12);
await db.query(
`
INSERT INTO users (username, password, role)
VALUES (?, ?, ?)
`,
[username, passwordHash, 'user']
);
return res.json({
code: 0,
message: '创建成功'
});
} catch (error) {
if (error.code === 'DUPLICATE_USERNAME') {
return res.status(409).json({
code: 40003,
message: '用户名已存在'
});
}
console.error(error);
return res.status(500).json({
code: 500,
message: '服务暂时不可用,请稍后重试'
});
}
});
This code mainly solves several problems:
- Basic validation of username and password.
- Using a hash value to store the password.
- Using parameterized queries to avoid direct SQL concatenation.
- Not allowing users to modify roles through parameters.
- Handling duplicate usernames separately.
- Not directly exposing database error information.
Note that the database error code and db.query writing style in the example should be adjusted according to the database driver actually used in the project.
AI-generated modified code also cannot be directly copied and used; it must still be verified in the project environment.
7. Before submission, don't just review the code itself
In addition to the code, you should also tell AI the scope of this modification.
For example:
The requirement this time is to add a user registration interface.
Modified files:
- src/routes/user.js
- src/services/userService.js
- test/user.test.js
Not modified:
- Database table structure
- Login logic
- Frontend pages
Please check:
1. Whether content outside the requirement scope has been modified.
2. Whether interface tests are missing.
3. Whether interface documentation needs to be updated synchronously.
4. Whether it may affect the existing login functionality.
This helps AI focus on "whether this submission is complete," rather than just checking a certain piece of code.
If the project uses Git, you can also give AI the diff of this modification:
git diff -- src/routes/user.js src/services/userService.js
Then send the output to AI:
Below is the code diff for this submission.
Please check:
1. Whether it meets the requirements.
2. Whether it introduces new functional problems.
3. Whether there are security risks.
4. Whether tests or documentation are missing.
5. Whether it contains unrelated modifications.
Please only list issues that need attention, do not rewrite the entire project.
The benefit of using diff review is that AI can focus on "what has changed," reducing analysis of unrelated code.
8. The correct sequence for AI code review
It is recommended to use AI in the following order:
Clarify requirements and acceptance criteria
↓
Complete a small-scope code modification
↓
Run code and tests yourself
↓
Let AI review the code or diff
↓
Confirm problem priorities
↓
Fix problems and retest
↓
Submit code and wait for manual review
Do not let AI complete all judgments for you before the code has even basically run.
AI is more suitable for helping us discover omissions, rather than deciding for us whether code can go live.
9. Pre-submission code review checklist
You can save the following checklist and confirm item by item before submission:
Functionality check
- Whether it meets the original requirements.
- Whether normal input gets correct results.
- Whether failure scenarios have clear prompts.
- Whether null values and wrong types are handled.
- Whether duplicate data is handled.
- Whether it affects existing functionality.
Security check
- Whether there is SQL injection risk.
- Whether there is XSS risk.
- Whether permission checks are performed.
- Whether privilege escalation operations are possible.
- Whether passwords are stored securely.
- Whether keys, tokens, or cookies are committed.
- Whether sensitive error information is exposed to the frontend.
Engineering check
- Whether necessary tests have been added.
- Whether relevant documentation has been updated.
- Whether debug code and temporary logs have been deleted.
- Whether unrelated files have been modified.
- Whether it conforms to project code standards.
- Whether it has been verified by local execution.
Summary
AI can help us discover some problems before submitting code, and is especially suitable for checking the following:
- Functionality and logic errors.
- Common security risks.
- Boundary conditions and exception handling.
- Code style and maintainability.
- Tests, documentation, and modification scope.
High-quality AI code review requires providing complete requirements, code, tech stack, and acceptance criteria.
At the same time, do not treat AI's review results as the final conclusion. For security, permissions, data processing, and core business logic, developers and the team still need to perform manual confirmation.
You can remember one sentence:
Let AI help you find problems, but you decide whether the problem is real, whether it is important, and how it should be fixed.
The next article will introduce:
"Privacy and Security in AI Programming: What Information Not to Submit"
✍Insist on original content, seeking follows, likes, and favorites