惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The Register - Security
The Register - Security
云风的 BLOG
云风的 BLOG
U
Unit 42
F
Fortinet All Blogs
The GitHub Blog
The GitHub Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
D
Docker
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
S
Secure Thoughts
Hacker News: Ask HN
Hacker News: Ask HN
Vercel News
Vercel News
S
Security @ Cisco Blogs
GbyAI
GbyAI
Stack Overflow Blog
Stack Overflow Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
I
Intezer
MongoDB | Blog
MongoDB | Blog
AI
AI
MyScale Blog
MyScale Blog
Engineering at Meta
Engineering at Meta
Y
Y Combinator Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Proofpoint News Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
W
WeLiveSecurity
博客园 - 叶小钗
S
SegmentFault 最新的问题
N
News | PayPal Newsroom
WordPress大学
WordPress大学
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
D
DataBreaches.Net
小众软件
小众软件
Microsoft Azure Blog
Microsoft Azure Blog
Spread Privacy
Spread Privacy
H
Help Net Security
美团技术团队
博客园 - 司徒正美
T
Threat Research - Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
K
Kaspersky official blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
V
Vulnerabilities – Threatpost
TaoSecurity Blog
TaoSecurity Blog
N
Netflix TechBlog - Medium
L
Lohrmann on Cybersecurity
J
Java Code Geeks
量子位
Martin Fowler
Martin Fowler
博客园_首页

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Agentic Code Generation with OpenAI Codex CLI — A Knight's Tour Walkthrough
Malcolm Low · 2026-05-16 · via DEV Community

Malcolm Low

Originally published on malcolmlow.net

A step-by-step walkthrough of using OpenAI's agentic coding tool to scaffold, solve, test, and visualise the classic Knight's Tour chess problem — entirely through natural language prompts.

This post assumes you have Codex CLI installed and authenticated. We'll be working in three phases, each driven by a carefully crafted Codex prompt.


♞ What is the Knight's Tour Problem?

The Knight's Tour is a classic puzzle from combinatorics and graph theory: given an n×n chessboard and a knight placed on any starting square, can the knight visit every square on the board exactly once using only valid knight moves? A knight moves in an L-shape — two squares in one direction and one square perpendicular, giving it up to eight possible moves from any position.

The problem has been studied for over a thousand years. Arab mathematicians documented it as early as the 9th century, and Leonhard Euler conducted a systematic mathematical analysis in 1759. There are two variants: an open tour, where the starting and ending squares differ, and a closed (re-entrant) tour, where the knight can return to its starting square in one move. On the standard 8×8 board, there are over 26 trillion distinct open tours.

From an algorithmic standpoint, the Knight's Tour is a special case of the Hamiltonian path problem on a graph, where each square is a node and edges connect squares reachable by a knight move. Finding a Hamiltonian path is NP-complete in general, but the regular structure of the chessboard makes efficient heuristics possible.

The most well-known heuristic is Warnsdorff's rule (H.C. von Warnsdorff, 1823): at each step, move to the unvisited square that has the fewest onward moves. This greedy approach runs in linear time relative to the number of squares and finds a tour almost always on boards of size 5×5 and above.


🗺️ What We're Building

Phase What Codex Builds Output
Phase 1 Core solver using Warnsdorff's heuristic CLI app, ASCII board output
Phase 2 Pytest test suite and colourised terminal output ANSI colour board, passing tests
Phase 3 Flask web app with animated HTML canvas Interactive browser visualisation

⚙️ Prerequisites

Before starting, make sure you have:

  • Codex CLI installed (brew install --cask codex or npm i -g @openai/codex)
  • Authenticated with a ChatGPT Plus/Pro account or an OpenAI API key
  • Python 3.10+ available in your shell
  • Git installed on your machine

📁 Project Setup

We'll use Git throughout this guide as a safety net. Configure your identity first if needed:

git config --global user.name  "Your Name"
git config --global user.email "you@example.com"

Enter fullscreen mode Exit fullscreen mode

Create the project directory and initialise the repo:

mkdir knights-tour && cd knights-tour
git init
git commit --allow-empty -m "initial commit"
codex

Enter fullscreen mode Exit fullscreen mode

Once the TUI loads, generate an AGENTS.md file first. It acts as a standing project-level system prompt — Codex reads it automatically at the start of every future session.

📝 Codex Prompt — Generate AGENTS.md

"Create an AGENTS.md file in the project root for a Python CLI and web application project. Include the following standing instructions: use Python 3.10+ with type hints throughout; place all tests in a /tests directory using pytest; never use global mutable state; prefer functions over classes unless OOP is genuinely the better fit; handle all CLI arguments with argparse; use Flask for any web routes; keep each module focused on a single responsibility."

Why prompt Codex to write AGENTS.md instead of writing it yourself? You describe your intent conversationally rather than worrying about format, and it sets the right mental model for the rest of the guide. You can update it at any time: "Add a rule that all functions must have docstrings" — Codex will edit the file in place.


Phase 1 — Core Solver

📝 Codex Prompt — Phase 1

"Create a Python CLI app that solves the Knight's Tour problem. Use Warnsdorff's heuristic: at each step, move to the unvisited square with the fewest onward moves. The board size and starting position (row, col) should be configurable via argparse with defaults of n=8, row=0, col=0. The solver should return None if no tour is found. Display the completed board as a grid of move numbers, right-aligned. Save the solver logic in knight_tour.py and the entry point in main.py. Include a requirements.txt and a .gitignore for Python."

Here's a simplified version of what the generated knight_tour.py looks like:

MOVES = [(2,1),(2,-1),(-2,1),(-2,-1),(1,2),(1,-2),(-1,2),(-1,-2)]

def get_neighbours(x, y, n, visited):
    return [(x+dx, y+dy) for dx,dy in MOVES
            if 0 <= x+dx < n and 0 <= y+dy < n
            and not visited[x+dx][y+dy]]

def solve(n, start_x, start_y):
    visited = [[False]*n for _ in range(n)]
    board   = [[-1]*n   for _ in range(n)]
    x, y = start_x, start_y
    visited[x][y] = True
    board[x][y]   = 0
    for move in range(1, n*n):
        neighbours = get_neighbours(x, y, n, visited)
        if not neighbours:
            return None
        x, y = min(neighbours,
                   key=lambda p: len(get_neighbours(p[0],p[1],n,visited)))
        visited[x][y] = True
        board[x][y]   = move
    return board

Enter fullscreen mode Exit fullscreen mode

Run it to verify:

python3 main.py --size 8 --row 0 --col 0

Enter fullscreen mode Exit fullscreen mode

💡 Approval Flow: In Codex's default Auto mode, press A to accept or R to reject each diff. If Codex proposes something you don't want, reject and follow up with a corrective prompt — it retains full context.


Phase 2 — Tests & Colourised Output

📝 Codex Prompt — Phase 2

"Now add two things. First, create a test suite in tests/test_knight_tour.py using pytest. Test that: (1) solve() returns a valid tour where every integer from 0 to n²−1 appears exactly once, (2) consecutive moves are a valid knight's move apart, (3) solve() returns None for n=2 which has no solution. Second, add a new function print_coloured_board() in knight_tour.py that uses ANSI escape codes to colour the board — alternate between a light and dark background for a chess-style pattern, with white text for the move numbers. Call it from main.py instead of format_board() when --colour flag is passed."

Key tests:

import pytest
from knight_tour import solve

def is_valid_knight_move(x1, y1, x2, y2):
    dx, dy = abs(x2-x1), abs(y2-y1)
    return (dx, dy) in {(1,2),(2,1)}

@pytest.mark.parametrize("n,r,c", [(5,0,0),(6,1,1),(8,0,0),(8,3,4)])
def test_valid_tour(n, r, c):
    board = solve(n, r, c)
    assert board is not None
    flat = sorted(v for row in board for v in row)
    assert flat == list(range(n*n))

def test_no_solution_n2():
    assert solve(2, 0, 0) is None

Enter fullscreen mode Exit fullscreen mode

Install pytest and run:

pip3 install pytest
pytest tests/ -v
python3 main.py --size 8 --colour

Enter fullscreen mode Exit fullscreen mode


Phase 3 — Flask Web App with Animated Visualisation

📝 Codex Prompt — Phase 3

"Add a Flask web app in app.py. It needs two routes: GET / serves a single-page HTML form where users can input board size (5–10) and starting row/col. POST /solve accepts these inputs, runs the solver, and returns the board as JSON. The HTML page should also contain a JavaScript canvas visualisation that animates the knight's path one move at a time — draw the board as a grid, colour visited squares progressively, and draw a ♞ symbol on the current square. Add flask to requirements.txt."

The key backend endpoint:

from flask import Flask, request, jsonify, render_template_string
from knight_tour import solve
app = Flask(__name__)

@app.route("/solve", methods=["POST"])
def solve_tour():
    data = request.get_json()
    n, row, col = int(data.get("size",8)), int(data.get("row",0)), int(data.get("col",0))
    if not (5 <= n <= 10):
        return jsonify({"error": "Board size must be between 5 and 10"}), 400
    board = solve(n, row, col)
    if board is None:
        return jsonify({"error": "No solution found"}), 422
    return jsonify({"board": board, "n": n})

Enter fullscreen mode Exit fullscreen mode

pip3 install flask
python3 app.py
# Visit http://localhost:5000

Enter fullscreen mode Exit fullscreen mode


🔄 Iterating Further — More Prompt Ideas

Goal Follow-up Prompt
Speed comparison "Add a backtracking solver as an alternative to Warnsdorff's. Add a --solver flag to switch between them, and time both with Python's timeit."
Export result "Add a --export flag to main.py that saves the board as a CSV and a PNG using matplotlib, with the knight path drawn as a line."
User clicks board "Update the web app so users click a cell on the canvas to set the starting position instead of using the form fields."
Code review "Review the current codebase for edge cases, type annotation completeness, and any issues with input validation in app.py."

✅ Effective Prompting Tips for Codex

Tip Why It Helps
Name your files explicitly Codex won't guess at naming conventions — "save to knight_tour.py" prevents arbitrary filenames.
Specify what None/failure means Without "return None if no tour is found," Codex might raise an exception instead.
Bundle related changes in one prompt Codex handles multi-file tasks well when given in a single cohesive prompt.
Keep sessions alive for follow-ups Staying in the same session means Codex retains full context — no re-explaining.
Use AGENTS.md for standing rules Anything you'd say in every prompt belongs in AGENTS.md. It keeps prompts shorter and style consistent.

📁 Final Project Structure

knights-tour/
├── AGENTS.md
├── .gitignore
├── requirements.txt      ← flask
├── knight_tour.py        ← solver + display logic
├── main.py               ← CLI entry point
├── app.py                ← Flask web app
└── tests/
    └── test_knight_tour.py

Enter fullscreen mode Exit fullscreen mode

The workflow rhythm: each Codex prompt builds on the last without re-explaining context, and AGENTS.md silently enforces project conventions. The three phases took roughly 15 minutes end-to-end, most of which was reviewing diffs and running tests rather than writing code.

The Knight's Tour is just the illustration. The same prompt-iterate-commit loop applies to any project — and the more you invest in a good AGENTS.md upfront, the more useful each Codex session becomes.