From 60021afeb7d536a8c4d29f8ebd1e40e6ee1a9714 Mon Sep 17 00:00:00 2001 From: Kang Tu Date: Tue, 22 Sep 2026 10:46:03 -0700 Subject: [PATCH 1/6] Add emit-prompt helper for ai-code-prompt-mode buffers --- ai-code-doc.el | 28 ++++++++++++++++++----- test/test_ai-code-doc.el | 48 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 6 deletions(-) diff --git a/ai-code-doc.el b/ai-code-doc.el index e9c7134d..ad314de6 100644 --- a/ai-code-doc.el +++ b/ai-code-doc.el @@ -28,6 +28,21 @@ ("Derive Test Context Document" . ai-code-derive-test-context)) "Choices for `ai-code-derive-architecture-document'.") +(defun ai-code-doc--emit-prompt (title prompt) + "Insert PROMPT under a TITLE headline at point, or send it to the AI. +In `ai-code-prompt-mode' the prompt is written into the current buffer +under the cursor, as an Org section at the level of the surrounding +section, and no AI request is made. Everywhere else PROMPT is handed to +`ai-code--insert-prompt' as usual." + (if (derived-mode-p 'ai-code-prompt-mode) + (let ((level (or (org-current-level) 1))) + (unless (bolp) + (insert "\n")) + (insert (make-string level ?*) " " title " ") + (org-insert-time-stamp (current-time) t t) + (insert "\n" prompt "\n")) + (ai-code--insert-prompt prompt))) + ;;;###autoload (defun ai-code-derive-architecture-document () "Derive an architecture document by selecting one of the available options." @@ -312,8 +327,8 @@ Default value is English." (if-let ((final-prompt (ai-code-plain-read-string "Prompt: " initial-prompt))) (progn - (ai-code--insert-prompt final-prompt) - (message "Requested architecture guardrails for %s" git-root)) + (ai-code-doc--emit-prompt "Derive Architecture Guardrails" final-prompt) + (message "Architecture guardrails prompt ready for %s" git-root)) (message "Architecture guardrails request cancelled"))))) ;;;###autoload @@ -332,7 +347,7 @@ not already exist, so the backend has a concrete document to create or update." (final-prompt (ai-code-plain-read-string "Derive DDD context prompt: " initial-prompt))) (when final-prompt - (ai-code--insert-prompt final-prompt))))) + (ai-code-doc--emit-prompt "Derive DDD Context for Repo" final-prompt))))) ;;;###autoload (defun ai-code-derive-test-context () @@ -350,7 +365,7 @@ not already exist, so the backend has a concrete document to create or update." (final-prompt (ai-code-plain-read-string "Derive Test Context prompt: " initial-prompt))) (when final-prompt - (ai-code--insert-prompt final-prompt))))) + (ai-code-doc--emit-prompt "Derive Test Context Document" final-prompt))))) ;;;###autoload (defun ai-code-derive-c4-plantuml () @@ -368,7 +383,8 @@ not already exist, so the backend has a concrete document to create or update." (final-prompt (ai-code-plain-read-string "Derive C4 PlantUML prompt: " initial-prompt))) (when final-prompt - (ai-code--insert-prompt final-prompt))))) + (ai-code-doc--emit-prompt "Derive C4 PlantUML Architecture Document" + final-prompt))))) ;;;###autoload (defun ai-code-derive-repo-map () @@ -386,7 +402,7 @@ not already exist, so the backend has a concrete document to create or update." (final-prompt (ai-code-plain-read-string "Derive repository map prompt: " initial-prompt))) (when final-prompt - (ai-code--insert-prompt final-prompt))))) + (ai-code-doc--emit-prompt "Derive Repository Map" final-prompt))))) (provide 'ai-code-doc) ;;; ai-code-doc.el ends here diff --git a/test/test_ai-code-doc.el b/test/test_ai-code-doc.el index c39360ce..1e731cc1 100644 --- a/test/test_ai-code-doc.el +++ b/test/test_ai-code-doc.el @@ -373,6 +373,54 @@ everything is cleaned up afterward." (should (string-match-p (regexp-quote "Generate the document in German.") captured-final-prompt)))))) +(ert-deftest ai-code-test-derive-ddd-context-inserts-into-prompt-mode-buffer () + "In `ai-code-prompt-mode' the DDD prompt is written at point instead of sent." + (ai-code-file-with-test-env + (let (sent-prompt) + (cl-letf (((symbol-function 'ai-code--git-root) + (lambda (&optional _dir) default-directory)) + ((symbol-function 'read-string) + (lambda (&rest _args) "English")) + ((symbol-function 'ai-code-plain-read-string) + (lambda (_prompt &optional initial-input) initial-input)) + ((symbol-function 'ai-code--insert-prompt) + (lambda (prompt) (setq sent-prompt prompt)))) + (with-temp-buffer + (ai-code-prompt-mode) + (insert "* Existing task\n** Sub task\n") + (goto-char (point-max)) + (ai-code-derive-ddd-context) + (should-not sent-prompt) + (should (string-match-p "^\\*\\* Derive DDD Context for Repo \\[" + (buffer-string))) + (should (string-match-p + (regexp-quote "Domain-Driven Design (DDD) style context document") + (buffer-string)))))))) + +(ert-deftest ai-code-test-derive-architecture-guardrails-inserts-into-prompt-mode-buffer () + "In `ai-code-prompt-mode' the guardrails prompt is written at point, not sent." + (ai-code-file-with-test-env + (let (sent-prompt) + (cl-letf (((symbol-function 'ai-code--git-root) + (lambda (&optional _dir) default-directory)) + ((symbol-function 'read-string) + (lambda (&rest _args) "English")) + ((symbol-function 'ai-code-plain-read-string) + (lambda (_prompt initial-input) initial-input)) + ((symbol-function 'ai-code--insert-prompt) + (lambda (prompt) (setq sent-prompt prompt)))) + (with-temp-buffer + (ai-code-prompt-mode) + (insert "* Existing task\n") + (goto-char (point-max)) + (ai-code-derive-architecture-guardrails) + (should-not sent-prompt) + (should (string-match-p "^\\* Derive Architecture Guardrails \\[" + (buffer-string))) + (should (string-match-p + (regexp-quote "Derive a lightweight architecture guardrails document") + (buffer-string)))))))) + (provide 'test_ai-code-doc) ;;; test_ai-code-doc.el ends here ;;; test_ai-code-doc.el ends here From 9777fa6162deb91c84bbc8d47a647ba18a50f3c2 Mon Sep 17 00:00:00 2001 From: Kang Tu Date: Tue, 22 Sep 2026 11:15:05 -0700 Subject: [PATCH 2/6] Add optional topic scoping to architecture document commands --- ai-code-doc.el | 145 +++++++++++++++++++++++++++------------ test/test_ai-code-doc.el | 103 ++++++++++++++++++++++----- 2 files changed, 187 insertions(+), 61 deletions(-) diff --git a/ai-code-doc.el b/ai-code-doc.el index ad314de6..edd53e55 100644 --- a/ai-code-doc.el +++ b/ai-code-doc.el @@ -65,6 +65,44 @@ Default value is English." "Prompt for the language and append it to BASE-PROMPT." (concat base-prompt (format "\nGenerate the document in %s." (ai-code--read-document-language)))) +(defun ai-code--read-document-topic () + "Ask which topic the document should cover. +Return nil for an empty answer, which means the whole repository." + (let ((topic (string-trim + (read-string "Document topic (empty for whole repo): ")))) + (unless (string-empty-p topic) topic))) + +(defun ai-code--topic-file-name (file-name topic) + "Return FILE-NAME with a slug of TOPIC added to its base name. +FILE-NAME is returned unchanged when TOPIC is nil, so whole-repository +documents keep their well-known path and topic documents never overwrite +them." + (if topic + (let ((slug (string-trim + (downcase (replace-regexp-in-string "[^A-Za-z0-9]+" "-" topic)) + "-+" "-+"))) + (format "%s-%s.%s" + (file-name-sans-extension file-name) + (if (string-empty-p slug) "topic" slug) + (file-name-extension file-name))) + file-name)) + +(defun ai-code--append-document-topic (base-prompt topic) + "Append TOPIC scoping instructions to BASE-PROMPT. +BASE-PROMPT is returned unchanged when TOPIC is nil." + (if topic + (concat base-prompt + (format "\nScope this document to the topic: %s.\n" topic) + "Only cover the code, tests, and docs relevant to this topic, and state which parts of the repository are out of scope.\n") + base-prompt)) + +(defun ai-code--finalize-document-prompt (base-prompt topic) + "Append the TOPIC scope and the document language to BASE-PROMPT. +The topic is added first so that the language question stays the last one +asked before the prompt is edited." + (ai-code--append-document-language + (ai-code--append-document-topic base-prompt topic))) + (defconst ai-code-ddd-context-output-relative-path ".ai.code.files/architecture/domain-context.org" "Repository-relative path for the derived DDD context document.") @@ -120,8 +158,9 @@ Default value is English." (write-region "" nil target-file nil 'silent)) target-file)) -(defun ai-code--derive-ddd-context-prompt (git-root) - "Build and return a formatted DDD context derivation prompt string for GIT-ROOT." +(defun ai-code--derive-ddd-context-prompt (git-root &optional topic) + "Build and return a formatted DDD context derivation prompt string for GIT-ROOT. +TOPIC narrows the output file name when non-nil." (concat "Derive a lightweight Domain-Driven Design (DDD) style context document for this existing repository.\n" "Do not assume the repository already follows DDD today.\n" @@ -133,7 +172,7 @@ Default value is English." "When referencing any code file, function, variable, or type, you MUST provide a relative Org-mode link in the format [[file:../../path/to/file::symbol_or_line][description_text]] pointing to its definition in the codebase (relative to the .ai.code.files/architecture/ output directory).\n" (format "Repository root: %s\n" git-root) (format "Create or update the Org file at %s.\n\n" - ai-code-ddd-context-output-relative-path) + (ai-code--topic-file-name ai-code-ddd-context-output-relative-path topic)) "Use this structure:\n" "* Domain Context\n\n" "** Purpose\n" @@ -145,8 +184,9 @@ Default value is English." "** Testing Ideas\n" "** Notes and Uncertainties")) -(defun ai-code--derive-test-context-prompt (git-root) - "Build and return Test Context prompt for GIT-ROOT." +(defun ai-code--derive-test-context-prompt (git-root &optional topic) + "Build and return Test Context prompt for GIT-ROOT. +TOPIC narrows the output file name when non-nil." (concat "Derive a lightweight Test Context and Verification Guide document for this existing repository.\n" "Analyze the existing tests, test runner configuration, and mocking/verification patterns.\n" @@ -155,7 +195,7 @@ Default value is English." "When referencing any test file, source file, test case, function, variable, or type, you MUST provide a relative Org-mode link in the format [[file:../../path/to/file::symbol_or_line][description_text]] pointing to its definition in the codebase (relative to the .ai.code.files/architecture/ output directory).\n" (format "Repository root: %s\n" git-root) (format "Create or update the Org file at %s.\n\n" - ai-code-test-context-output-relative-path) + (ai-code--topic-file-name ai-code-test-context-output-relative-path topic)) "Use this structure:\n" "* Test Context and Verification Guide\n\n" "** Purpose\n" @@ -166,8 +206,9 @@ Default value is English." "** Coverage Gaps & Actionable Testing Ideas\n" "** Notes and Uncertainties")) -(defun ai-code--derive-c4-plantuml-prompt (git-root) - "Build and return a C4 PlantUML architecture document prompt for GIT-ROOT." +(defun ai-code--derive-c4-plantuml-prompt (git-root &optional topic) + "Build and return a C4 PlantUML architecture document prompt for GIT-ROOT. +TOPIC narrows the output file name when non-nil." (concat "Derive a C4-style architecture overview document for this existing repository.\n" "Generate the document as Org mode and embed PlantUML C4 diagrams in Org Babel source blocks.\n" @@ -183,7 +224,7 @@ Default value is English." "Use PlantUML C4 includes such as !include , !include , and !include when appropriate.\n" (format "Repository root: %s\n" git-root) (format "Create or update the Org file at %s.\n\n" - ai-code-c4-plantuml-output-relative-path) + (ai-code--topic-file-name ai-code-c4-plantuml-output-relative-path topic)) "Use this Org structure:\n" "#+TITLE: C4 Architecture Overview\n\n" "* Purpose\n" @@ -211,8 +252,9 @@ Default value is English." "* Source Evidence\n" "Provide a table mapping important claims to Org links pointing at source evidence.")) -(defun ai-code--derive-repo-map-prompt (git-root) - "Build and return a repository map derivation prompt for GIT-ROOT." +(defun ai-code--derive-repo-map-prompt (git-root &optional topic) + "Build and return a repository map derivation prompt for GIT-ROOT. +TOPIC narrows the output file name when non-nil." (concat "Derive a lightweight Repository Map document for this existing repository.\n" "The primary goal is to help a new human contributor or AI coding agent quickly understand how to read and navigate the codebase.\n" @@ -228,7 +270,7 @@ Default value is English." "Use Org Babel PlantUML blocks with :file when adding diagrams.\n" (format "Repository root: %s\n" git-root) (format "Create or update the Org file at %s.\n\n" - ai-code-repo-map-output-relative-path) + (ai-code--topic-file-name ai-code-repo-map-output-relative-path topic)) "Use this Org structure:\n" "#+TITLE: Repository Map\n\n" "* Purpose\n" @@ -258,22 +300,27 @@ Default value is English." "* Source Evidence\n" "Provide a table mapping important claims to Org links pointing at source evidence.")) -(defun ai-code--architecture-guardrails-relative-path () - "Return the repo-relative path for the architecture guardrails file." +(defun ai-code--architecture-guardrails-relative-path (&optional topic) + "Return the repo-relative path for the architecture guardrails file. +TOPIC narrows the file name when non-nil." (concat ai-code-files-dir-name "/" ai-code-file--architecture-guardrails-directory-name "/" - ai-code-file--architecture-guardrails-file-name)) - -(defun ai-code--architecture-guardrails-file-path () - "Return the absolute path for the architecture guardrails file." - (expand-file-name ai-code-file--architecture-guardrails-file-name + (ai-code--topic-file-name + ai-code-file--architecture-guardrails-file-name topic))) + +(defun ai-code--architecture-guardrails-file-path (&optional topic) + "Return the absolute path for the architecture guardrails file. +TOPIC narrows the file name when non-nil." + (expand-file-name (ai-code--topic-file-name + ai-code-file--architecture-guardrails-file-name topic) (expand-file-name ai-code-file--architecture-guardrails-directory-name (ai-code--ensure-files-directory)))) -(defun ai-code--ensure-architecture-guardrails-file () - "Create the architecture guardrails file with a starter template if missing." - (let ((target-file (ai-code--architecture-guardrails-file-path))) +(defun ai-code--ensure-architecture-guardrails-file (&optional topic) + "Create the architecture guardrails file with a starter template if missing. +TOPIC narrows the file name when non-nil." + (let ((target-file (ai-code--architecture-guardrails-file-path topic))) (unless (file-directory-p (file-name-directory target-file)) (make-directory (file-name-directory target-file) t)) (unless (file-exists-p target-file) @@ -281,9 +328,10 @@ Default value is English." (insert ai-code-file--architecture-guardrails-template))) target-file)) -(defun ai-code--build-architecture-guardrails-prompt (git-root) - "Build the default prompt to derive architecture guardrails for GIT-ROOT." - (let ((relative-path (ai-code--architecture-guardrails-relative-path))) +(defun ai-code--build-architecture-guardrails-prompt (git-root &optional topic) + "Build the default prompt to derive architecture guardrails for GIT-ROOT. +TOPIC narrows the output file name when non-nil." + (let ((relative-path (ai-code--architecture-guardrails-relative-path topic))) (mapconcat #'identity (list "Derive a lightweight architecture guardrails document for this existing repository." @@ -321,9 +369,10 @@ Default value is English." (let ((git-root (ai-code--git-root))) (unless git-root (user-error "Not in a git repository")) - (ai-code--ensure-architecture-guardrails-file) - (let* ((base-prompt (ai-code--build-architecture-guardrails-prompt git-root)) - (initial-prompt (ai-code--append-document-language base-prompt))) + (let* ((topic (ai-code--read-document-topic)) + (base-prompt (ai-code--build-architecture-guardrails-prompt git-root topic)) + (initial-prompt (ai-code--finalize-document-prompt base-prompt topic))) + (ai-code--ensure-architecture-guardrails-file topic) (if-let ((final-prompt (ai-code-plain-read-string "Prompt: " initial-prompt))) (progn @@ -338,12 +387,14 @@ The target Org file under `.ai.code.files/architecture/' is created if it does not already exist, so the backend has a concrete document to create or update." (interactive) (let* ((git-root (or (ai-code--git-root) - (user-error "Not inside a Git repository")))) - (ai-code--ensure-architecture-document-file "domain-context.org") + (user-error "Not inside a Git repository"))) + (topic (ai-code--read-document-topic))) + (ai-code--ensure-architecture-document-file + (ai-code--topic-file-name "domain-context.org" topic)) (let* ((base-prompt - (concat (ai-code--derive-ddd-context-prompt git-root) + (concat (ai-code--derive-ddd-context-prompt git-root topic) (or (ai-code--format-repo-context-info) ""))) - (initial-prompt (ai-code--append-document-language base-prompt)) + (initial-prompt (ai-code--finalize-document-prompt base-prompt topic)) (final-prompt (ai-code-plain-read-string "Derive DDD context prompt: " initial-prompt))) (when final-prompt @@ -356,12 +407,14 @@ The target Org file under `.ai.code.files/architecture/' is created if it does not already exist, so the backend has a concrete document to create or update." (interactive) (let* ((git-root (or (ai-code--git-root) - (user-error "Not inside a Git repository")))) - (ai-code--ensure-architecture-document-file "test-context.org") + (user-error "Not inside a Git repository"))) + (topic (ai-code--read-document-topic))) + (ai-code--ensure-architecture-document-file + (ai-code--topic-file-name "test-context.org" topic)) (let* ((base-prompt - (concat (ai-code--derive-test-context-prompt git-root) + (concat (ai-code--derive-test-context-prompt git-root topic) (or (ai-code--format-repo-context-info) ""))) - (initial-prompt (ai-code--append-document-language base-prompt)) + (initial-prompt (ai-code--finalize-document-prompt base-prompt topic)) (final-prompt (ai-code-plain-read-string "Derive Test Context prompt: " initial-prompt))) (when final-prompt @@ -374,12 +427,14 @@ The target Org file under `.ai.code.files/architecture/' is created if it does not already exist, so the backend has a concrete document to create or update." (interactive) (let* ((git-root (or (ai-code--git-root) - (user-error "Not inside a Git repository")))) - (ai-code--ensure-architecture-document-file "c4-overview.org") + (user-error "Not inside a Git repository"))) + (topic (ai-code--read-document-topic))) + (ai-code--ensure-architecture-document-file + (ai-code--topic-file-name "c4-overview.org" topic)) (let* ((base-prompt - (concat (ai-code--derive-c4-plantuml-prompt git-root) + (concat (ai-code--derive-c4-plantuml-prompt git-root topic) (or (ai-code--format-repo-context-info) ""))) - (initial-prompt (ai-code--append-document-language base-prompt)) + (initial-prompt (ai-code--finalize-document-prompt base-prompt topic)) (final-prompt (ai-code-plain-read-string "Derive C4 PlantUML prompt: " initial-prompt))) (when final-prompt @@ -393,12 +448,14 @@ The target Org file under `.ai.code.files/architecture/' is created if it does not already exist, so the backend has a concrete document to create or update." (interactive) (let* ((git-root (or (ai-code--git-root) - (user-error "Not inside a Git repository")))) - (ai-code--ensure-architecture-document-file "repo-map.org") + (user-error "Not inside a Git repository"))) + (topic (ai-code--read-document-topic))) + (ai-code--ensure-architecture-document-file + (ai-code--topic-file-name "repo-map.org" topic)) (let* ((base-prompt - (concat (ai-code--derive-repo-map-prompt git-root) + (concat (ai-code--derive-repo-map-prompt git-root topic) (or (ai-code--format-repo-context-info) ""))) - (initial-prompt (ai-code--append-document-language base-prompt)) + (initial-prompt (ai-code--finalize-document-prompt base-prompt topic)) (final-prompt (ai-code-plain-read-string "Derive repository map prompt: " initial-prompt))) (when final-prompt diff --git a/test/test_ai-code-doc.el b/test/test_ai-code-doc.el index 1e731cc1..798d13a1 100644 --- a/test/test_ai-code-doc.el +++ b/test/test_ai-code-doc.el @@ -40,6 +40,12 @@ everything is cleaned up afterward." (when (file-directory-p test-dir) (delete-directory test-dir t))))) +(defun ai-code-test--doc-read-string (topic language) + "Return a `read-string' stand-in answering TOPIC and LANGUAGE. +The document topic question is recognized by its prompt prefix." + (lambda (prompt &rest _args) + (if (string-prefix-p "Document topic" prompt) topic language))) + (ert-deftest ai-code-test-menu-agile-development-includes-derive-architecture-document-entry () "Test that Agile Development menu exposes architecture document derivation." (let ((suffix (transient-get-suffix 'ai-code--menu-agile-development "A"))) @@ -102,7 +108,7 @@ everything is cleaned up afterward." (lambda (&optional _dir) tmp-root)) ((symbol-function 'read-string) - (lambda (&rest _args) "English")) + (ai-code-test--doc-read-string "" "English")) ((symbol-function 'ai-code-plain-read-string) (lambda (prompt initial-input) (should (equal prompt "Prompt: ")) @@ -152,7 +158,7 @@ everything is cleaned up afterward." (lambda (&optional _dir) tmp-root)) ((symbol-function 'read-string) - (lambda (&rest _args) "English")) + (ai-code-test--doc-read-string "" "English")) ((symbol-function 'ai-code-plain-read-string) (lambda (_prompt initial-input) initial-input)) @@ -182,7 +188,7 @@ everything is cleaned up afterward." (lambda (&optional _dir) tmp-root)) ((symbol-function 'read-string) - (lambda (&rest _args) "English")) + (ai-code-test--doc-read-string "" "English")) ((symbol-function 'ai-code-plain-read-string) (lambda (_prompt _initial-input) nil)) @@ -209,7 +215,7 @@ everything is cleaned up afterward." (lambda (&optional _dir) default-directory)) ((symbol-function 'read-string) - (lambda (&rest _args) "English")) + (ai-code-test--doc-read-string "" "English")) ((symbol-function 'ai-code-plain-read-string) (lambda (prompt &optional initial-input) (setq captured-read-prompt prompt @@ -226,6 +232,8 @@ everything is cleaned up afterward." (should (string-match-p "\\.ai\\.code\\.files/architecture/domain-context\\.org" captured-initial-prompt)) + (should-not (string-match-p "Scope this document to the topic" + captured-initial-prompt)) (should (string-match-p "\\*\\* Notes and Uncertainties" captured-initial-prompt)) (should (string-match-p (regexp-quote "[[file:../../path/to/file::symbol_or_line][description_text]]") @@ -243,7 +251,7 @@ everything is cleaned up afterward." (lambda (&optional _dir) default-directory)) ((symbol-function 'read-string) - (lambda (&rest _args) "English")) + (ai-code-test--doc-read-string "" "English")) ((symbol-function 'ai-code--format-repo-context-info) (lambda () "\nStored repository context:\n - Preserve existing CLI UX")) @@ -275,7 +283,7 @@ everything is cleaned up afterward." (lambda (&optional _dir) default-directory)) ((symbol-function 'read-string) - (lambda (&rest _args) "English")) + (ai-code-test--doc-read-string "" "English")) ((symbol-function 'ai-code-plain-read-string) (lambda (prompt &optional initial-input) (setq captured-read-prompt prompt @@ -311,9 +319,11 @@ everything is cleaned up afterward." (lambda (&optional _dir) tmp-root)) ((symbol-function 'read-string) (lambda (prompt &optional initial-input &rest _args) - (setq captured-language-prompt prompt - captured-language-default initial-input) - mock-lang)) + (if (string-prefix-p "Document topic" prompt) + "" + (setq captured-language-prompt prompt + captured-language-default initial-input) + mock-lang))) ((symbol-function 'ai-code-plain-read-string) (lambda (_prompt initial-input) initial-input)) ((symbol-function 'ai-code--insert-prompt) @@ -336,9 +346,11 @@ everything is cleaned up afterward." (lambda (&optional _dir) default-directory)) ((symbol-function 'read-string) (lambda (prompt &optional initial-input &rest _args) - (setq captured-language-prompt prompt - captured-language-default initial-input) - mock-lang)) + (if (string-prefix-p "Document topic" prompt) + "" + (setq captured-language-prompt prompt + captured-language-default initial-input) + mock-lang))) ((symbol-function 'ai-code-plain-read-string) (lambda (_prompt initial-input) initial-input)) ((symbol-function 'ai-code--insert-prompt) @@ -360,9 +372,11 @@ everything is cleaned up afterward." (lambda (&optional _dir) default-directory)) ((symbol-function 'read-string) (lambda (prompt &optional initial-input &rest _args) - (setq captured-language-prompt prompt - captured-language-default initial-input) - mock-lang)) + (if (string-prefix-p "Document topic" prompt) + "" + (setq captured-language-prompt prompt + captured-language-default initial-input) + mock-lang))) ((symbol-function 'ai-code-plain-read-string) (lambda (_prompt initial-input) initial-input)) ((symbol-function 'ai-code--insert-prompt) @@ -380,7 +394,7 @@ everything is cleaned up afterward." (cl-letf (((symbol-function 'ai-code--git-root) (lambda (&optional _dir) default-directory)) ((symbol-function 'read-string) - (lambda (&rest _args) "English")) + (ai-code-test--doc-read-string "" "English")) ((symbol-function 'ai-code-plain-read-string) (lambda (_prompt &optional initial-input) initial-input)) ((symbol-function 'ai-code--insert-prompt) @@ -404,7 +418,7 @@ everything is cleaned up afterward." (cl-letf (((symbol-function 'ai-code--git-root) (lambda (&optional _dir) default-directory)) ((symbol-function 'read-string) - (lambda (&rest _args) "English")) + (ai-code-test--doc-read-string "" "English")) ((symbol-function 'ai-code-plain-read-string) (lambda (_prompt initial-input) initial-input)) ((symbol-function 'ai-code--insert-prompt) @@ -421,6 +435,61 @@ everything is cleaned up afterward." (regexp-quote "Derive a lightweight architecture guardrails document") (buffer-string)))))))) +(ert-deftest ai-code-test-derive-ddd-context-scopes-to-topic () + "A non-empty document topic narrows the DDD prompt and its output file." + (ai-code-file-with-test-env + (let (captured-topic-prompt + inserted-prompt) + (cl-letf (((symbol-function 'ai-code--git-root) + (lambda (&optional _dir) default-directory)) + ((symbol-function 'read-string) + (lambda (prompt &rest _args) + (cond ((string-prefix-p "Document topic" prompt) + (setq captured-topic-prompt prompt) + "Prompt Pipeline") + (t "English")))) + ((symbol-function 'ai-code-plain-read-string) + (lambda (_prompt &optional initial-input) initial-input)) + ((symbol-function 'ai-code--insert-prompt) + (lambda (prompt) (setq inserted-prompt prompt)))) + (ai-code-derive-ddd-context) + (should (equal captured-topic-prompt + "Document topic (empty for whole repo): ")) + (should (string-match-p + (regexp-quote "Scope this document to the topic: Prompt Pipeline") + inserted-prompt)) + (should (string-match-p + (regexp-quote ".ai.code.files/architecture/domain-context-prompt-pipeline.org") + inserted-prompt)) + (should (file-exists-p + (expand-file-name + ".ai.code.files/architecture/domain-context-prompt-pipeline.org" + default-directory))))))) + +(ert-deftest ai-code-test-derive-architecture-guardrails-scopes-to-topic () + "A non-empty document topic narrows the guardrails prompt and its output file." + (ai-code-file-with-test-env + (let (inserted-prompt) + (cl-letf (((symbol-function 'ai-code--git-root) + (lambda (&optional _dir) default-directory)) + ((symbol-function 'read-string) + (ai-code-test--doc-read-string "Git Integration" "English")) + ((symbol-function 'ai-code-plain-read-string) + (lambda (_prompt initial-input) initial-input)) + ((symbol-function 'ai-code--insert-prompt) + (lambda (prompt) (setq inserted-prompt prompt)))) + (ai-code-derive-architecture-guardrails) + (should (string-match-p + (regexp-quote "Scope this document to the topic: Git Integration") + inserted-prompt)) + (should (string-match-p + (regexp-quote "@.ai.code.files/architecture/guardrails-git-integration.org") + inserted-prompt)) + (should (file-exists-p + (expand-file-name + ".ai.code.files/architecture/guardrails-git-integration.org" + default-directory))))))) + (provide 'test_ai-code-doc) ;;; test_ai-code-doc.el ends here ;;; test_ai-code-doc.el ends here From 519b122daa41845bade75baad0d7eb67caa0fda3 Mon Sep 17 00:00:00 2001 From: Kang Tu Date: Tue, 22 Sep 2026 11:31:24 -0700 Subject: [PATCH 3/6] Extract Org link instruction into depth-aware helper --- ai-code-doc.el | 25 ++++++++++++++++++++----- test/test_ai-code-doc.el | 35 ++++++++++++++++++++++++++++++++--- 2 files changed, 52 insertions(+), 8 deletions(-) diff --git a/ai-code-doc.el b/ai-code-doc.el index edd53e55..79ba1b8d 100644 --- a/ai-code-doc.el +++ b/ai-code-doc.el @@ -148,6 +148,21 @@ asked before the prompt is edited." "\n") "Initial Org template for architecture guardrails.") +(defun ai-code--org-link-instruction (output-relative-path) + "Return the Org link rules for a document written to OUTPUT-RELATIVE-PATH. +Links are relative to the document itself, so one \"../\" is needed per +directory level OUTPUT-RELATIVE-PATH sits in below the repository root." + (let* ((depth (length (split-string + (or (file-name-directory output-relative-path) "") + "/" t))) + (prefix (apply #'concat (make-list depth "../")))) + (concat + (format "When referencing any file, folder, module, function, variable, type, or test case, you MUST write it as a relative Org-mode link in the format [[file:%spath/to/file::symbol][description]] so that the reader can jump from the document straight to the code.\n" + prefix) + "Point each link at the definition: use ::symbol as the search target, and fall back to :: only when there is no named symbol to search for.\n" + "Only link to paths and symbols you have actually confirmed in the repository; when you cannot confirm a definition, say so in plain text instead of guessing a link.\n" + "Add the link at the first mention in each section, in every table cell that names a file or a symbol, and in the explanatory notes that follow each diagram.\n"))) + (defun ai-code--ensure-architecture-document-file (file-name) "Ensure an architecture document named FILE-NAME exists and return its path." (let* ((files-dir (ai-code--ensure-files-directory)) @@ -169,7 +184,7 @@ TOPIC narrows the output file name when non-nil." "Mark uncertainty explicitly.\n" "Keep the output practical, concise, and useful for future AI coding tasks.\n" "Do not suggest large refactors unless you list them separately as optional future ideas.\n" - "When referencing any code file, function, variable, or type, you MUST provide a relative Org-mode link in the format [[file:../../path/to/file::symbol_or_line][description_text]] pointing to its definition in the codebase (relative to the .ai.code.files/architecture/ output directory).\n" + (ai-code--org-link-instruction ai-code-ddd-context-output-relative-path) (format "Repository root: %s\n" git-root) (format "Create or update the Org file at %s.\n\n" (ai-code--topic-file-name ai-code-ddd-context-output-relative-path topic)) @@ -192,7 +207,7 @@ TOPIC narrows the output file name when non-nil." "Analyze the existing tests, test runner configuration, and mocking/verification patterns.\n" "Explain how the tests demonstrate and safeguard core business invariants.\n" "Keep the output practical, concise, and useful for future AI coding tasks.\n" - "When referencing any test file, source file, test case, function, variable, or type, you MUST provide a relative Org-mode link in the format [[file:../../path/to/file::symbol_or_line][description_text]] pointing to its definition in the codebase (relative to the .ai.code.files/architecture/ output directory).\n" + (ai-code--org-link-instruction ai-code-test-context-output-relative-path) (format "Repository root: %s\n" git-root) (format "Create or update the Org file at %s.\n\n" (ai-code--topic-file-name ai-code-test-context-output-relative-path topic)) @@ -218,7 +233,7 @@ TOPIC narrows the output file name when non-nil." "Mark uncertain boundaries, relationships, and naming choices explicitly.\n" "Prefer fewer boxes and clearer relationships over large, noisy diagrams.\n" "Use C4 only as an architectural draft for human review.\n" - "When referencing any code file, folder, module, function, variable, or type, you MUST provide a relative Org-mode link in the format [[file:../../path/to/file::symbol_or_line][description_text]] pointing to its definition in the codebase (relative to the .ai.code.files/architecture/ output directory).\n" + (ai-code--org-link-instruction ai-code-c4-plantuml-output-relative-path) "For every diagram, include explanatory notes after the PlantUML block that summarize what the diagram shows and what remains uncertain.\n" "Use Org Babel blocks like #+begin_src plantuml :file c4-context.svg :exports both and include @startuml / @enduml inside each block.\n" "Use PlantUML C4 includes such as !include , !include , and !include when appropriate.\n" @@ -265,7 +280,7 @@ TOPIC narrows the output file name when non-nil." "Mark uncertainty explicitly when a file or directory purpose is inferred rather than documented.\n" "Prefer practical guidance over abstract architecture theory.\n" "Keep the document concise enough to be reused in future AI coding prompts.\n" - "When referencing any code file, folder, module, function, variable, or type, you MUST provide a relative Org-mode link in the format [[file:../../path/to/file::symbol_or_line][description_text]] pointing to its definition in the codebase (relative to the .ai.code.files/architecture/ output directory).\n" + (ai-code--org-link-instruction ai-code-repo-map-output-relative-path) "Use text and tables as the main format. Include at most two small PlantUML diagrams only when they improve navigation: one top-level dependency or module graph, and optionally one suggested reading-path graph.\n" "Use Org Babel PlantUML blocks with :file when adding diagrams.\n" (format "Repository root: %s\n" git-root) @@ -346,7 +361,7 @@ TOPIC narrows the output file name when non-nil." "Focus on what helps future AI coding sessions avoid breaking boundaries or introducing messy dependencies." "Do not suggest large refactors unless clearly separated as optional future ideas." "Keep it concise, practical, and small enough to reuse in future AI prompts." - "When referencing any code file, folder, module, function, variable, or type, you MUST provide a relative Org-mode link in the format [[file:../../path/to/file::symbol_or_line][description]] pointing to its definition in the codebase (relative to the .ai.code.files/architecture/ output directory)." + (string-trim-right (ai-code--org-link-instruction relative-path)) "" "Use this Org structure:" "#+TITLE: Architecture Guardrails" diff --git a/test/test_ai-code-doc.el b/test/test_ai-code-doc.el index 798d13a1..dc4843ae 100644 --- a/test/test_ai-code-doc.el +++ b/test/test_ai-code-doc.el @@ -139,7 +139,7 @@ The document topic question is recognized by its prompt prefix." captured-initial-prompt)) (should (string-match-p (regexp-quote "Org-mode format") captured-initial-prompt)) - (should (string-match-p (regexp-quote "[[file:../../path/to/file::symbol_or_line][description]]") + (should (string-match-p (regexp-quote "[[file:../../path/to/file::symbol][description]]") captured-initial-prompt)) (should (equal captured-final-prompt captured-initial-prompt))) (ignore-errors (delete-directory tmp-root t))))) @@ -236,7 +236,7 @@ The document topic question is recognized by its prompt prefix." captured-initial-prompt)) (should (string-match-p "\\*\\* Notes and Uncertainties" captured-initial-prompt)) - (should (string-match-p (regexp-quote "[[file:../../path/to/file::symbol_or_line][description_text]]") + (should (string-match-p (regexp-quote "[[file:../../path/to/file::symbol][description]]") captured-initial-prompt)) (should (equal inserted-prompt captured-initial-prompt)) (should (file-exists-p @@ -300,7 +300,7 @@ The document topic question is recognized by its prompt prefix." (should (string-match-p "\\.ai\\.code\\.files/architecture/test-context\\.org" captured-initial-prompt)) - (should (string-match-p (regexp-quote "[[file:../../path/to/file::symbol_or_line][description_text]]") + (should (string-match-p (regexp-quote "[[file:../../path/to/file::symbol][description]]") captured-initial-prompt)) (should (equal inserted-prompt captured-initial-prompt)) (should (file-exists-p @@ -490,6 +490,35 @@ The document topic question is recognized by its prompt prefix." ".ai.code.files/architecture/guardrails-git-integration.org" default-directory))))))) +(ert-deftest ai-code-test-document-prompts-require-verified-org-links () + "Every derived document prompt asks for verified relative Org links." + (dolist (builder '(ai-code--derive-ddd-context-prompt + ai-code--derive-test-context-prompt + ai-code--derive-c4-plantuml-prompt + ai-code--derive-repo-map-prompt + ai-code--build-architecture-guardrails-prompt)) + (let ((prompt (funcall builder "/tmp/repo"))) + (should (string-match-p + (regexp-quote "[[file:../../path/to/file::symbol][description]]") + prompt)) + (should (string-match-p + (regexp-quote "fall back to :: only when") + prompt)) + (should (string-match-p + (regexp-quote "Only link to paths and symbols you have actually confirmed") + prompt)) + (should (string-match-p (regexp-quote "first mention in each section") + prompt))))) + +(ert-deftest ai-code-test-org-link-instruction-prefix-follows-output-depth () + "The relative link prefix is derived from the document output depth." + (should (string-match-p (regexp-quote "[[file:../../path/to/file::symbol]") + (ai-code--org-link-instruction "a/b/doc.org"))) + (should (string-match-p (regexp-quote "[[file:../path/to/file::symbol]") + (ai-code--org-link-instruction "a/doc.org"))) + (should (string-match-p (regexp-quote "[[file:path/to/file::symbol]") + (ai-code--org-link-instruction "doc.org")))) + (provide 'test_ai-code-doc) ;;; test_ai-code-doc.el ends here ;;; test_ai-code-doc.el ends here From 7b3e9c54820c762759df9134a49d86fe4a33f133 Mon Sep 17 00:00:00 2001 From: Kang Tu Date: Tue, 22 Sep 2026 15:56:42 -0700 Subject: [PATCH 4/6] Add GitHub link style option to architecture docs --- ai-code-doc.el | 114 +++++++++++++++++++++++++++++++++++-------------- 1 file changed, 83 insertions(+), 31 deletions(-) diff --git a/ai-code-doc.el b/ai-code-doc.el index 79ba1b8d..2a4a9114 100644 --- a/ai-code-doc.el +++ b/ai-code-doc.el @@ -19,6 +19,7 @@ (declare-function ai-code--format-repo-context-info "ai-code-utils") (declare-function ai-code--git-root "ai-code-utils" (&optional dir)) (declare-function ai-code--ensure-files-directory "ai-code-utils") +(declare-function ai-code--get-git-web-repo-url "ai-code-github" ()) (defconst ai-code--architecture-document-choices '(("Derive Architecture Guardrails" . ai-code-derive-architecture-guardrails) @@ -148,18 +149,58 @@ asked before the prompt is edited." "\n") "Initial Org template for architecture guardrails.") -(defun ai-code--org-link-instruction (output-relative-path) +(defun ai-code--doc-github-repo-url () + "Return the GitHub web URL of the current repository, or nil. +Only GitHub remotes are recognized, because the generated links use the +GitHub /blob/HEAD/ URL shape. Any failure to reach Git or to parse the +remote simply yields nil, which keeps documents on local file links." + (ignore-errors + (require 'ai-code-github) + (let ((url (ai-code--get-git-web-repo-url))) + (when (and url (string-match-p "\\`https://[^/]*github[^/]*/" url)) + url)))) + +(defun ai-code--read-document-link-style () + "Ask whether code references should link to GitHub or to local files. +Return `github' or `local'. The question is skipped when the repository +has no GitHub remote, because only local links can work then." + (if (and (ai-code--doc-github-repo-url) + (string-prefix-p + "g" + (string-trim (read-string "Link code references to (github or local): " + "github")) + t)) + 'github + 'local)) + +(defun ai-code--org-link-instruction (output-relative-path &optional link-style) "Return the Org link rules for a document written to OUTPUT-RELATIVE-PATH. -Links are relative to the document itself, so one \"../\" is needed per -directory level OUTPUT-RELATIVE-PATH sits in below the repository root." +LINK-STYLE is `github' to prefer browser links, and anything else keeps +the document on local file links. Local links to files inside the +repository are relative to the document itself, so one \"../\" is needed +per directory level OUTPUT-RELATIVE-PATH sits in below the repository +root; files outside the repository have no such anchor and are linked by +absolute path." (let* ((depth (length (split-string (or (file-name-directory output-relative-path) "") "/" t))) - (prefix (apply #'concat (make-list depth "../")))) + (prefix (apply #'concat (make-list depth "../"))) + (local-rules + (concat + (format "For a file inside this repository, use a relative link: [[file:%spath/to/file::symbol][description]].\n" + prefix) + "For a file outside this repository, use an absolute link: [[file:/absolute/path/to/file::symbol][description]].\n")) + (repo-url (and (eq link-style 'github) (ai-code--doc-github-repo-url)))) (concat - (format "When referencing any file, folder, module, function, variable, type, or test case, you MUST write it as a relative Org-mode link in the format [[file:%spath/to/file::symbol][description]] so that the reader can jump from the document straight to the code.\n" - prefix) - "Point each link at the definition: use ::symbol as the search target, and fall back to :: only when there is no named symbol to search for.\n" + "When referencing any file, folder, module, function, variable, type, or test case, you MUST turn it into a link so that the reader can jump from the document straight to the code.\n" + (if repo-url + (concat + (format "Use a GitHub link, which opens in a browser: [[%s/blob/HEAD/path/to/file#L42][description]], anchored at the line where the definition starts.\n" + repo-url) + "When the code is not on the GitHub remote, for example an untracked, ignored, or generated file, fall back to a local link instead:\n" + local-rules) + local-rules) + "Point each link at the definition: in a local link use ::symbol as the search target, and fall back to :: only when there is no named symbol to search for.\n" "Only link to paths and symbols you have actually confirmed in the repository; when you cannot confirm a definition, say so in plain text instead of guessing a link.\n" "Add the link at the first mention in each section, in every table cell that names a file or a symbol, and in the explanatory notes that follow each diagram.\n"))) @@ -173,9 +214,10 @@ directory level OUTPUT-RELATIVE-PATH sits in below the repository root." (write-region "" nil target-file nil 'silent)) target-file)) -(defun ai-code--derive-ddd-context-prompt (git-root &optional topic) +(defun ai-code--derive-ddd-context-prompt (git-root &optional topic link-style) "Build and return a formatted DDD context derivation prompt string for GIT-ROOT. -TOPIC narrows the output file name when non-nil." +TOPIC narrows the output file name when non-nil, and LINK-STYLE +selects how code references are linked." (concat "Derive a lightweight Domain-Driven Design (DDD) style context document for this existing repository.\n" "Do not assume the repository already follows DDD today.\n" @@ -184,7 +226,7 @@ TOPIC narrows the output file name when non-nil." "Mark uncertainty explicitly.\n" "Keep the output practical, concise, and useful for future AI coding tasks.\n" "Do not suggest large refactors unless you list them separately as optional future ideas.\n" - (ai-code--org-link-instruction ai-code-ddd-context-output-relative-path) + (ai-code--org-link-instruction ai-code-ddd-context-output-relative-path link-style) (format "Repository root: %s\n" git-root) (format "Create or update the Org file at %s.\n\n" (ai-code--topic-file-name ai-code-ddd-context-output-relative-path topic)) @@ -199,15 +241,16 @@ TOPIC narrows the output file name when non-nil." "** Testing Ideas\n" "** Notes and Uncertainties")) -(defun ai-code--derive-test-context-prompt (git-root &optional topic) +(defun ai-code--derive-test-context-prompt (git-root &optional topic link-style) "Build and return Test Context prompt for GIT-ROOT. -TOPIC narrows the output file name when non-nil." +TOPIC narrows the output file name when non-nil, and LINK-STYLE +selects how code references are linked." (concat "Derive a lightweight Test Context and Verification Guide document for this existing repository.\n" "Analyze the existing tests, test runner configuration, and mocking/verification patterns.\n" "Explain how the tests demonstrate and safeguard core business invariants.\n" "Keep the output practical, concise, and useful for future AI coding tasks.\n" - (ai-code--org-link-instruction ai-code-test-context-output-relative-path) + (ai-code--org-link-instruction ai-code-test-context-output-relative-path link-style) (format "Repository root: %s\n" git-root) (format "Create or update the Org file at %s.\n\n" (ai-code--topic-file-name ai-code-test-context-output-relative-path topic)) @@ -221,9 +264,10 @@ TOPIC narrows the output file name when non-nil." "** Coverage Gaps & Actionable Testing Ideas\n" "** Notes and Uncertainties")) -(defun ai-code--derive-c4-plantuml-prompt (git-root &optional topic) +(defun ai-code--derive-c4-plantuml-prompt (git-root &optional topic link-style) "Build and return a C4 PlantUML architecture document prompt for GIT-ROOT. -TOPIC narrows the output file name when non-nil." +TOPIC narrows the output file name when non-nil, and LINK-STYLE +selects how code references are linked." (concat "Derive a C4-style architecture overview document for this existing repository.\n" "Generate the document as Org mode and embed PlantUML C4 diagrams in Org Babel source blocks.\n" @@ -233,7 +277,7 @@ TOPIC narrows the output file name when non-nil." "Mark uncertain boundaries, relationships, and naming choices explicitly.\n" "Prefer fewer boxes and clearer relationships over large, noisy diagrams.\n" "Use C4 only as an architectural draft for human review.\n" - (ai-code--org-link-instruction ai-code-c4-plantuml-output-relative-path) + (ai-code--org-link-instruction ai-code-c4-plantuml-output-relative-path link-style) "For every diagram, include explanatory notes after the PlantUML block that summarize what the diagram shows and what remains uncertain.\n" "Use Org Babel blocks like #+begin_src plantuml :file c4-context.svg :exports both and include @startuml / @enduml inside each block.\n" "Use PlantUML C4 includes such as !include , !include , and !include when appropriate.\n" @@ -267,9 +311,10 @@ TOPIC narrows the output file name when non-nil." "* Source Evidence\n" "Provide a table mapping important claims to Org links pointing at source evidence.")) -(defun ai-code--derive-repo-map-prompt (git-root &optional topic) +(defun ai-code--derive-repo-map-prompt (git-root &optional topic link-style) "Build and return a repository map derivation prompt for GIT-ROOT. -TOPIC narrows the output file name when non-nil." +TOPIC narrows the output file name when non-nil, and LINK-STYLE +selects how code references are linked." (concat "Derive a lightweight Repository Map document for this existing repository.\n" "The primary goal is to help a new human contributor or AI coding agent quickly understand how to read and navigate the codebase.\n" @@ -280,7 +325,7 @@ TOPIC narrows the output file name when non-nil." "Mark uncertainty explicitly when a file or directory purpose is inferred rather than documented.\n" "Prefer practical guidance over abstract architecture theory.\n" "Keep the document concise enough to be reused in future AI coding prompts.\n" - (ai-code--org-link-instruction ai-code-repo-map-output-relative-path) + (ai-code--org-link-instruction ai-code-repo-map-output-relative-path link-style) "Use text and tables as the main format. Include at most two small PlantUML diagrams only when they improve navigation: one top-level dependency or module graph, and optionally one suggested reading-path graph.\n" "Use Org Babel PlantUML blocks with :file when adding diagrams.\n" (format "Repository root: %s\n" git-root) @@ -343,9 +388,10 @@ TOPIC narrows the file name when non-nil." (insert ai-code-file--architecture-guardrails-template))) target-file)) -(defun ai-code--build-architecture-guardrails-prompt (git-root &optional topic) +(defun ai-code--build-architecture-guardrails-prompt (git-root &optional topic link-style) "Build the default prompt to derive architecture guardrails for GIT-ROOT. -TOPIC narrows the output file name when non-nil." +TOPIC narrows the output file name when non-nil, and LINK-STYLE +selects how code references are linked." (let ((relative-path (ai-code--architecture-guardrails-relative-path topic))) (mapconcat #'identity @@ -361,7 +407,7 @@ TOPIC narrows the output file name when non-nil." "Focus on what helps future AI coding sessions avoid breaking boundaries or introducing messy dependencies." "Do not suggest large refactors unless clearly separated as optional future ideas." "Keep it concise, practical, and small enough to reuse in future AI prompts." - (string-trim-right (ai-code--org-link-instruction relative-path)) + (string-trim-right (ai-code--org-link-instruction relative-path link-style)) "" "Use this Org structure:" "#+TITLE: Architecture Guardrails" @@ -385,7 +431,9 @@ TOPIC narrows the output file name when non-nil." (unless git-root (user-error "Not in a git repository")) (let* ((topic (ai-code--read-document-topic)) - (base-prompt (ai-code--build-architecture-guardrails-prompt git-root topic)) + (link-style (ai-code--read-document-link-style)) + (base-prompt (ai-code--build-architecture-guardrails-prompt + git-root topic link-style)) (initial-prompt (ai-code--finalize-document-prompt base-prompt topic))) (ai-code--ensure-architecture-guardrails-file topic) (if-let ((final-prompt @@ -403,11 +451,12 @@ not already exist, so the backend has a concrete document to create or update." (interactive) (let* ((git-root (or (ai-code--git-root) (user-error "Not inside a Git repository"))) - (topic (ai-code--read-document-topic))) + (topic (ai-code--read-document-topic)) + (link-style (ai-code--read-document-link-style))) (ai-code--ensure-architecture-document-file (ai-code--topic-file-name "domain-context.org" topic)) (let* ((base-prompt - (concat (ai-code--derive-ddd-context-prompt git-root topic) + (concat (ai-code--derive-ddd-context-prompt git-root topic link-style) (or (ai-code--format-repo-context-info) ""))) (initial-prompt (ai-code--finalize-document-prompt base-prompt topic)) (final-prompt (ai-code-plain-read-string "Derive DDD context prompt: " @@ -423,11 +472,12 @@ not already exist, so the backend has a concrete document to create or update." (interactive) (let* ((git-root (or (ai-code--git-root) (user-error "Not inside a Git repository"))) - (topic (ai-code--read-document-topic))) + (topic (ai-code--read-document-topic)) + (link-style (ai-code--read-document-link-style))) (ai-code--ensure-architecture-document-file (ai-code--topic-file-name "test-context.org" topic)) (let* ((base-prompt - (concat (ai-code--derive-test-context-prompt git-root topic) + (concat (ai-code--derive-test-context-prompt git-root topic link-style) (or (ai-code--format-repo-context-info) ""))) (initial-prompt (ai-code--finalize-document-prompt base-prompt topic)) (final-prompt (ai-code-plain-read-string "Derive Test Context prompt: " @@ -443,11 +493,12 @@ not already exist, so the backend has a concrete document to create or update." (interactive) (let* ((git-root (or (ai-code--git-root) (user-error "Not inside a Git repository"))) - (topic (ai-code--read-document-topic))) + (topic (ai-code--read-document-topic)) + (link-style (ai-code--read-document-link-style))) (ai-code--ensure-architecture-document-file (ai-code--topic-file-name "c4-overview.org" topic)) (let* ((base-prompt - (concat (ai-code--derive-c4-plantuml-prompt git-root topic) + (concat (ai-code--derive-c4-plantuml-prompt git-root topic link-style) (or (ai-code--format-repo-context-info) ""))) (initial-prompt (ai-code--finalize-document-prompt base-prompt topic)) (final-prompt (ai-code-plain-read-string "Derive C4 PlantUML prompt: " @@ -464,11 +515,12 @@ not already exist, so the backend has a concrete document to create or update." (interactive) (let* ((git-root (or (ai-code--git-root) (user-error "Not inside a Git repository"))) - (topic (ai-code--read-document-topic))) + (topic (ai-code--read-document-topic)) + (link-style (ai-code--read-document-link-style))) (ai-code--ensure-architecture-document-file (ai-code--topic-file-name "repo-map.org" topic)) (let* ((base-prompt - (concat (ai-code--derive-repo-map-prompt git-root topic) + (concat (ai-code--derive-repo-map-prompt git-root topic link-style) (or (ai-code--format-repo-context-info) ""))) (initial-prompt (ai-code--finalize-document-prompt base-prompt topic)) (final-prompt (ai-code-plain-read-string "Derive repository map prompt: " From 54c726d3358f98968b3dc7feac4b0660806a43ff Mon Sep 17 00:00:00 2001 From: Kang Tu Date: Tue, 22 Sep 2026 16:31:59 -0700 Subject: [PATCH 5/6] Fix test failures caused by symlinked /tmp and /var on macOS --- test/test_ai-code-backends-infra.el | 35 +++++++++++++++++++++------- test/test_ai-code-editor-viewport.el | 9 +++++-- test/test_ai-code-harness.el | 12 ++++++++-- test/test_ai-code-session.el | 4 +++- 4 files changed, 47 insertions(+), 13 deletions(-) diff --git a/test/test_ai-code-backends-infra.el b/test/test_ai-code-backends-infra.el index 71536aa7..25bd1642 100644 --- a/test/test_ai-code-backends-infra.el +++ b/test/test_ai-code-backends-infra.el @@ -138,6 +138,13 @@ The result is a cons of whether SYMBOL is bound and its default value." (set-default symbol (cdr state)) (makunbound symbol))) +(defun test-ai-code-backends-infra--session-dir (directory) + "Return DIRECTORY the way session bookkeeping stores it. +Session keys are canonicalized with `file-truename', so a key built from a +literal path has to be resolved the same way to match. This matters where +the platform makes the literal path a symlink, such as /tmp on macOS." + (file-name-as-directory (file-truename directory))) + (ert-deftest test-ai-code-backends-infra-output-meaningful-p-noise () "Ensure terminal noise is not considered meaningful output." (should-not (ai-code-backends-infra--output-meaningful-p nil)) @@ -2059,7 +2066,9 @@ The prefix argument should also force instance-name prompting." nil "echo hi") (should (eq captured-table ai-code-backends-infra--processes)) - (should (eq (gethash (cons working-dir "default") + (should (eq (gethash (cons (test-ai-code-backends-infra--session-dir + working-dir) + "default") ai-code-backends-infra--processes) 'mock-process))) (when (buffer-live-p buffer) @@ -2075,7 +2084,9 @@ The prefix argument should also force instance-name prompting." (cleanup-count 0)) (unwind-protect (progn - (puthash (cons working-dir "default") process process-table) + (puthash (cons (test-ai-code-backends-infra--session-dir working-dir) + "default") + process process-table) (cl-letf (((symbol-function 'process-live-p) (lambda (candidate) (eq candidate process))) ((symbol-function 'ai-code-backends-infra--reuse-existing-session) @@ -2355,7 +2366,8 @@ The prefix argument should also force instance-name prompting." (should (equal (plist-get context :buffer-name) "*codex[ai-code-session-target:review]*")) (should (equal (plist-get context :session-key) - (cons working-dir "review"))) + (cons (test-ai-code-backends-infra--session-dir working-dir) + "review"))) (should-not prompt-called)))) (ert-deftest test-ai-code-backends-infra-resolve-session-target-does-not-prefill-prompt-buffer-filename () @@ -2398,7 +2410,8 @@ The prefix argument should also force instance-name prompting." (should (equal (plist-get context :buffer-name) "*codex[ai-code-session-target:manual-session]*")) (should (equal (plist-get context :session-key) - (cons working-dir "manual-session"))))) + (cons (test-ai-code-backends-infra--session-dir working-dir) + "manual-session"))))) (ert-deftest test-ai-code-backends-infra-resolve-session-target-prefills-source-buffer-branch () "Source buffers should seed new instance names from the current branch." @@ -2463,7 +2476,8 @@ The prefix argument should also force instance-name prompting." (should (equal (plist-get context :buffer-name) "*codex[ai-code-session-target:feat/first-session]*")) (should (equal (plist-get context :session-key) - (cons working-dir "feat/first-session"))))) + (cons (test-ai-code-backends-infra--session-dir working-dir) + "feat/first-session"))))) (ert-deftest test-ai-code-backends-infra-resolve-session-target-sanitizes-branch-name () "Branch-derived instance names should keep session buffer names parseable." @@ -2518,7 +2532,8 @@ The prefix argument should also force instance-name prompting." (should (equal (plist-get context :buffer-name) "*codex[ai-code-session-target]*")) (should (equal (plist-get context :session-key) - (cons working-dir "default"))))) + (cons (test-ai-code-backends-infra--session-dir working-dir) + "default"))))) (ert-deftest test-ai-code-backends-infra-resolve-session-context-includes-runtime-state () "Resolved session context should include target data plus buffer and process." @@ -2530,7 +2545,9 @@ The prefix argument should also force instance-name prompting." (context nil)) (unwind-protect (progn - (puthash (cons working-dir "default") process process-table) + (puthash (cons (test-ai-code-backends-infra--session-dir working-dir) + "default") + process process-table) (setq context (ai-code-backends-infra--resolve-session-context working-dir @@ -2542,7 +2559,9 @@ The prefix argument should also force instance-name prompting." (should (equal (plist-get context :instance-name) "default")) (should (equal (plist-get context :buffer-name) buffer-name)) (should (equal (plist-get context :session-key) - (cons working-dir "default"))) + (cons (test-ai-code-backends-infra--session-dir + working-dir) + "default"))) (should (eq (plist-get context :buffer) buffer)) (should (eq (plist-get context :existing-process) process))) (when (buffer-live-p buffer) diff --git a/test/test_ai-code-editor-viewport.el b/test/test_ai-code-editor-viewport.el index 618baf99..678ad199 100644 --- a/test/test_ai-code-editor-viewport.el +++ b/test/test_ai-code-editor-viewport.el @@ -62,10 +62,15 @@ Give the source side window WIDTH columns, defaulting to 40." :viewport-window (plist-get display-state :window)))) (defun ai-code-editor-viewport-test--transpose-parent-if-supported (window) - "Transpose WINDOW's parent when the current Emacs provides `window-x'." + "Transpose WINDOW's parent when the current Emacs and layout allow it. +`window-layout-transpose' needs `window-x', which only ships with newer +Emacs versions, and it refuses layouts holding a dedicated, fixed size or +atomic window, which side windows are. Both cases only cost the caller +the extra stress of a rearranged layout, so they are ignored here." (when (require 'window-x nil t) (let ((ignore-window-parameters t)) - (window-layout-transpose (window-parent window))))) + (ignore-error user-error + (window-layout-transpose (window-parent window)))))) (ert-deftest test-ai-code-editor-viewport--mode-uses-one-yank-key () "Viewport users should paste every supported clipboard type with `C-y'." diff --git a/test/test_ai-code-harness.el b/test/test_ai-code-harness.el index 52209b04..0b629c84 100644 --- a/test/test_ai-code-harness.el +++ b/test/test_ai-code-harness.el @@ -43,6 +43,14 @@ "--eval" form))) (list exit-code (buffer-string)))))) +(defun ai-code-harness-test--error-reported-p (output) + "Return non-nil when OUTPUT contains an Emacs \"Error:\" report. +The match is case sensitive on purpose: `case-fold-search' defaults to t +in batch mode, so a case-insensitive search also matches lower-case +\"error:\" text in platform noise the inferior Emacs writes to stderr." + (let ((case-fold-search nil)) + (string-match-p "Error:" output))) + (defun ai-code-harness-test--grill-context (origin-command) "Return a Grill prompt context for ORIGIN-COMMAND." (ai-code--make-prompt-context @@ -76,7 +84,7 @@ "'ai-code-code-change)) " "(kill-emacs 1)))")))) (should (equal exit-code 0)) - (should-not (string-match-p "Error:" output)))) + (should-not (ai-code-harness-test--error-reported-p output)))) (ert-deftest ai-code-test-grill-autoloaded-entry-loads-harness () "Loading an autoloaded entry module should install the Grill provider." @@ -98,7 +106,7 @@ "'ai-code-code-change)) " "(kill-emacs 1)))")))) (should (equal exit-code 0)) - (should-not (string-match-p "Error:" output)))) + (should-not (ai-code-harness-test--error-reported-p output)))) (ert-deftest ai-code-test-grill-harness-reload-removes-legacy-prompt-advice () "Reloading the harness should remove legacy Grill prompt advice." diff --git a/test/test_ai-code-session.el b/test/test_ai-code-session.el index 7b6652ac..6d16abf6 100644 --- a/test/test_ai-code-session.el +++ b/test/test_ai-code-session.el @@ -246,7 +246,9 @@ "D should open Magit status setup for the session repository." (ai-code-test-session--with-clean-registry (let ((session-buffer (get-buffer-create "*codex[diff]*")) - (repo-root (make-temp-file "ai-code-dashboard-diff-" t)) + ;; Resolve the temporary directory, because the dashboard reports the + ;; repository root canonicalized and /var is a symlink on macOS. + (repo-root (file-truename (make-temp-file "ai-code-dashboard-diff-" t))) dashboard-buffer opened-repo) (unwind-protect From ee3b567c29b5912e1e38bb8e83cf90a46a40c3a7 Mon Sep 17 00:00:00 2001 From: Kang Tu Date: Wed, 23 Sep 2026 07:58:32 -0700 Subject: [PATCH 6/6] Fix architecture document review feedback Pin GitHub source links to published commits and use local links when tracked content differs. Add stable topic digests, recognize ssh:// remotes with ports, and use the package-private prompt helper name. Add five regression tests. Strict byte compilation and checkdoc pass. The full suite has the same 28 failures and 13 skips as the unmodified PR baseline, with no new failures. --- ai-code-doc.el | 58 ++++++++++++------ ai-code-github.el | 17 ++++-- test/test_ai-code-doc.el | 113 ++++++++++++++++++++++++++++++++++-- test/test_ai-code-github.el | 18 ++++++ 4 files changed, 180 insertions(+), 26 deletions(-) diff --git a/ai-code-doc.el b/ai-code-doc.el index 2a4a9114..9e0518f4 100644 --- a/ai-code-doc.el +++ b/ai-code-doc.el @@ -20,6 +20,8 @@ (declare-function ai-code--git-root "ai-code-utils" (&optional dir)) (declare-function ai-code--ensure-files-directory "ai-code-utils") (declare-function ai-code--get-git-web-repo-url "ai-code-github" ()) +(declare-function magit-git-string "magit-git" (&rest args)) +(declare-function magit-git-success "magit-git" (&rest args)) (defconst ai-code--architecture-document-choices '(("Derive Architecture Guardrails" . ai-code-derive-architecture-guardrails) @@ -29,7 +31,7 @@ ("Derive Test Context Document" . ai-code-derive-test-context)) "Choices for `ai-code-derive-architecture-document'.") -(defun ai-code-doc--emit-prompt (title prompt) +(defun ai-code--doc-emit-prompt (title prompt) "Insert PROMPT under a TITLE headline at point, or send it to the AI. In `ai-code-prompt-mode' the prompt is written into the current buffer under the cursor, as an Org section at the level of the surrounding @@ -74,7 +76,8 @@ Return nil for an empty answer, which means the whole repository." (unless (string-empty-p topic) topic))) (defun ai-code--topic-file-name (file-name topic) - "Return FILE-NAME with a slug of TOPIC added to its base name. + "Return FILE-NAME with a slug and stable digest of TOPIC in its base name. +The digest distinguishes topics whose readable slugs are identical. FILE-NAME is returned unchanged when TOPIC is nil, so whole-repository documents keep their well-known path and topic documents never overwrite them." @@ -82,9 +85,12 @@ them." (let ((slug (string-trim (downcase (replace-regexp-in-string "[^A-Za-z0-9]+" "-" topic)) "-+" "-+"))) - (format "%s-%s.%s" + (format "%s-%s-%s.%s" (file-name-sans-extension file-name) (if (string-empty-p slug) "topic" slug) + (substring (secure-hash 'sha256 + (encode-coding-string topic 'utf-8)) + 0 12) (file-name-extension file-name))) file-name)) @@ -152,7 +158,7 @@ asked before the prompt is edited." (defun ai-code--doc-github-repo-url () "Return the GitHub web URL of the current repository, or nil. Only GitHub remotes are recognized, because the generated links use the -GitHub /blob/HEAD/ URL shape. Any failure to reach Git or to parse the +GitHub /blob/REVISION/ URL shape. Any failure to reach Git or to parse the remote simply yields nil, which keeps documents on local file links." (ignore-errors (require 'ai-code-github) @@ -160,11 +166,27 @@ remote simply yields nil, which keeps documents on local file links." (when (and url (string-match-p "\\`https://[^/]*github[^/]*/" url)) url)))) +(defun ai-code--doc-github-source-url () + "Return a GitHub URL pinned to the analyzed commit, or nil. +Require unchanged tracked files and an origin remote-tracking ref that +contains HEAD. Unpublished commits and Git failures use local links. +Remote-tracking refs are checked locally; no network request is made." + (ignore-errors + (let* ((repo-url (ai-code--doc-github-repo-url)) + (revision (and repo-url + (magit-git-string "rev-parse" "--verify" "HEAD")))) + (when (and revision + (magit-git-success "diff" "--quiet" revision "--") + (magit-git-string "for-each-ref" "--format=%(refname)" + (concat "--contains=" revision) + "refs/remotes/origin/")) + (format "%s/blob/%s" repo-url revision))))) + (defun ai-code--read-document-link-style () "Ask whether code references should link to GitHub or to local files. -Return `github' or `local'. The question is skipped when the repository -has no GitHub remote, because only local links can work then." - (if (and (ai-code--doc-github-repo-url) +Return `github' or `local'. Skip the question unless the analyzed commit +is known on a GitHub origin and tracked files are unchanged." + (if (and (ai-code--doc-github-source-url) (string-prefix-p "g" (string-trim (read-string "Link code references to (github or local): " @@ -190,14 +212,16 @@ absolute path." (format "For a file inside this repository, use a relative link: [[file:%spath/to/file::symbol][description]].\n" prefix) "For a file outside this repository, use an absolute link: [[file:/absolute/path/to/file::symbol][description]].\n")) - (repo-url (and (eq link-style 'github) (ai-code--doc-github-repo-url)))) + (source-url (and (eq link-style 'github) + (ai-code--doc-github-source-url)))) (concat "When referencing any file, folder, module, function, variable, type, or test case, you MUST turn it into a link so that the reader can jump from the document straight to the code.\n" - (if repo-url + (if source-url (concat - (format "Use a GitHub link, which opens in a browser: [[%s/blob/HEAD/path/to/file#L42][description]], anchored at the line where the definition starts.\n" - repo-url) - "When the code is not on the GitHub remote, for example an untracked, ignored, or generated file, fall back to a local link instead:\n" + (format "Use a GitHub link, which opens in a browser: [[%s/path/to/file#L42][description]], anchored at the line where the definition starts.\n" + source-url) + "Keep the commit ID in the URL; do not replace it with HEAD or a branch name. Verify that the referenced file and lines match this commit and that it is available on GitHub.\n" + "For files outside this repository, untracked, ignored, generated, or locally modified files, or when the commit is unavailable on GitHub, fall back to a local link instead:\n" local-rules) local-rules) "Point each link at the definition: in a local link use ::symbol as the search target, and fall back to :: only when there is no named symbol to search for.\n" @@ -439,7 +463,7 @@ selects how code references are linked." (if-let ((final-prompt (ai-code-plain-read-string "Prompt: " initial-prompt))) (progn - (ai-code-doc--emit-prompt "Derive Architecture Guardrails" final-prompt) + (ai-code--doc-emit-prompt "Derive Architecture Guardrails" final-prompt) (message "Architecture guardrails prompt ready for %s" git-root)) (message "Architecture guardrails request cancelled"))))) @@ -462,7 +486,7 @@ not already exist, so the backend has a concrete document to create or update." (final-prompt (ai-code-plain-read-string "Derive DDD context prompt: " initial-prompt))) (when final-prompt - (ai-code-doc--emit-prompt "Derive DDD Context for Repo" final-prompt))))) + (ai-code--doc-emit-prompt "Derive DDD Context for Repo" final-prompt))))) ;;;###autoload (defun ai-code-derive-test-context () @@ -483,7 +507,7 @@ not already exist, so the backend has a concrete document to create or update." (final-prompt (ai-code-plain-read-string "Derive Test Context prompt: " initial-prompt))) (when final-prompt - (ai-code-doc--emit-prompt "Derive Test Context Document" final-prompt))))) + (ai-code--doc-emit-prompt "Derive Test Context Document" final-prompt))))) ;;;###autoload (defun ai-code-derive-c4-plantuml () @@ -504,7 +528,7 @@ not already exist, so the backend has a concrete document to create or update." (final-prompt (ai-code-plain-read-string "Derive C4 PlantUML prompt: " initial-prompt))) (when final-prompt - (ai-code-doc--emit-prompt "Derive C4 PlantUML Architecture Document" + (ai-code--doc-emit-prompt "Derive C4 PlantUML Architecture Document" final-prompt))))) ;;;###autoload @@ -526,7 +550,7 @@ not already exist, so the backend has a concrete document to create or update." (final-prompt (ai-code-plain-read-string "Derive repository map prompt: " initial-prompt))) (when final-prompt - (ai-code-doc--emit-prompt "Derive Repository Map" final-prompt))))) + (ai-code--doc-emit-prompt "Derive Repository Map" final-prompt))))) (provide 'ai-code-doc) ;;; ai-code-doc.el ends here diff --git a/ai-code-github.el b/ai-code-github.el index 0ca563c6..224b0149 100644 --- a/ai-code-github.el +++ b/ai-code-github.el @@ -444,17 +444,26 @@ ARG is the optional prefix argument to force including context." "Get Git repository web URL from git remote. Returns the HTTPS URL of the repository for web browsing. Supports GitHub, GitLab, Bitbucket, and other Git hosting services. +Accepts HTTPS, SCP-style SSH, and ssh:// remotes, including SSH ports. Returns nil if unable to construct a web URL." (let* ((remote-url (magit-git-string "config" "--get" "remote.origin.url"))) (when (and remote-url (stringp remote-url) (not (string-empty-p remote-url))) (cond ;; HTTPS URL: https://host.com/user/repo.git or https://host.com/user/repo - ((string-match "https://\\([^/]+\\)/\\(.+\\)" remote-url) + ((string-match "\\`https://\\([^/]+\\)/\\(.+\\)\\'" remote-url) (let ((host (match-string 1 remote-url)) (path (match-string 2 remote-url))) (format "https://%s/%s" host (replace-regexp-in-string "\\.git$" "" path)))) - ;; SSH URL: git@host.com:user/repo.git or git@host.com:user/repo - ((string-match "git@\\([^:]+\\):\\(.+\\)" remote-url) + ;; SSH URI: ssh://git@host.com[:port]/user/repo.git + ;; An SSH transport port is not the web server's HTTPS port. + ((string-match + "\\`ssh://\\(?:[^/@]+@\\)?\\([^/:]+\\)\\(?::[0-9]+\\)?/\\(.+\\)\\'" + remote-url) + (let ((host (match-string 1 remote-url)) + (path (match-string 2 remote-url))) + (format "https://%s/%s" host (replace-regexp-in-string "\\.git$" "" path)))) + ;; SCP-style SSH: git@host.com:user/repo.git + ((string-match "\\`git@\\([^/:]+\\):\\(.+\\)\\'" remote-url) (let ((host (match-string 1 remote-url)) (path (match-string 2 remote-url))) (format "https://%s/%s" host (replace-regexp-in-string "\\.git$" "" path)))) @@ -509,4 +518,4 @@ Provide overall assessment. (provide 'ai-code-github) -;;; ai-code-github.el ends here \ No newline at end of file +;;; ai-code-github.el ends here diff --git a/test/test_ai-code-doc.el b/test/test_ai-code-doc.el index dc4843ae..944dbc2c 100644 --- a/test/test_ai-code-doc.el +++ b/test/test_ai-code-doc.el @@ -25,7 +25,7 @@ (require 'ai-code) (defmacro ai-code-file-with-test-env (&rest body) - "Set up a temporary environment for testing file operations. + "Run BODY in a temporary environment for testing file operations. This macro creates a temporary directory structure and ensures everything is cleaned up afterward." `(let* ((test-dir (expand-file-name "test-file-ops/" temporary-file-directory)) @@ -459,11 +459,11 @@ The document topic question is recognized by its prompt prefix." (regexp-quote "Scope this document to the topic: Prompt Pipeline") inserted-prompt)) (should (string-match-p - (regexp-quote ".ai.code.files/architecture/domain-context-prompt-pipeline.org") + (regexp-quote ".ai.code.files/architecture/domain-context-prompt-pipeline-13b070827c7b.org") inserted-prompt)) (should (file-exists-p (expand-file-name - ".ai.code.files/architecture/domain-context-prompt-pipeline.org" + ".ai.code.files/architecture/domain-context-prompt-pipeline-13b070827c7b.org" default-directory))))))) (ert-deftest ai-code-test-derive-architecture-guardrails-scopes-to-topic () @@ -483,11 +483,11 @@ The document topic question is recognized by its prompt prefix." (regexp-quote "Scope this document to the topic: Git Integration") inserted-prompt)) (should (string-match-p - (regexp-quote "@.ai.code.files/architecture/guardrails-git-integration.org") + (regexp-quote "@.ai.code.files/architecture/guardrails-git-integration-cd172722a457.org") inserted-prompt)) (should (file-exists-p (expand-file-name - ".ai.code.files/architecture/guardrails-git-integration.org" + ".ai.code.files/architecture/guardrails-git-integration-cd172722a457.org" default-directory))))))) (ert-deftest ai-code-test-document-prompts-require-verified-org-links () @@ -519,6 +519,109 @@ The document topic question is recognized by its prompt prefix." (should (string-match-p (regexp-quote "[[file:path/to/file::symbol]") (ai-code--org-link-instruction "doc.org")))) +(ert-deftest test-ai-code-doc--topic-file-name-distinguishes-lossy-slugs () + "Distinct topics must not update the same output document." + (let* ((topics '("\u8ba4\u8bc1" "\u652f\u4ed8" "C++" "C#" "c#")) + (paths (mapcar (lambda (topic) + (ai-code--topic-file-name "docs/domain-context.org" + topic)) + topics))) + (should (= (length topics) (length (delete-dups (copy-sequence paths))))) + (dolist (path paths) + (should (equal (file-name-directory path) "docs/")) + (should (equal (file-name-extension path) "org"))) + (should (equal (car paths) + (ai-code--topic-file-name "docs/domain-context.org" + (car topics)))))) + +(ert-deftest test-ai-code-doc--topic-file-name-preserves-repository-path () + "Whole-repository documents retain their established output path." + (should (equal (ai-code--topic-file-name "docs/domain-context.org" nil) + "docs/domain-context.org"))) + +(ert-deftest test-ai-code-doc--github-links-follow-analyzed-revision () + "Pin feature-branch links and use local links for unpublished or dirty code." + (let* ((repo (make-temp-file "ai-code-doc-git-" t)) + (default-directory (file-name-as-directory repo)) + (process-environment (append '("GIT_CONFIG_GLOBAL=/dev/null" + "GIT_CONFIG_NOSYSTEM=1") + process-environment))) + (unwind-protect + ;; Execute real Git queries even when other test files stub Magit. + (cl-letf (((symbol-function 'magit-git-string) + (lambda (&rest args) + (with-temp-buffer + (when (zerop (apply #'process-file "git" nil t nil args)) + (car (split-string (buffer-string) "\n" t)))))) + ((symbol-function 'magit-git-success) + (lambda (&rest args) + (zerop (apply #'process-file "git" nil nil nil args))))) + (cl-labels ((git (&rest args) + (should (zerop + (apply #'process-file "git" nil nil nil + "-c" "user.name=Document Test" + "-c" "user.email=doc@example.com" + "-c" "commit.gpgsign=false" args))))) + (git "init" "-q" "-b" "main") + (git "remote" "add" "origin" "ssh://git@github.com/org/repo.git") + ;; An unborn repository cannot supply a source revision. + (should-not (ai-code--doc-github-source-url)) + (with-temp-file "source.txt" (insert "Main definition\n")) + (with-temp-file ".gitignore" (insert "generated.txt\n")) + (git "add" ".") + (git "commit" "-qm" "Initial source") + (git "update-ref" "refs/remotes/origin/main" "HEAD") + (git "checkout" "-qb" "feature") + (with-temp-file "source.txt" (insert "Feature definition\n")) + (git "commit" "-qam" "Feature source") + ;; A commit on another remote does not prove origin has it. + (git "update-ref" "refs/remotes/upstream/feature" "HEAD") + (should-not (ai-code--doc-github-source-url)) + (cl-letf (((symbol-function 'read-string) + (lambda (&rest _) (ert-fail "Unexpected link question")))) + (should (eq (ai-code--read-document-link-style) 'local))) + (git "update-ref" "refs/remotes/origin/feature" "HEAD") + (let* ((revision (magit-git-string "rev-parse" "HEAD")) + (source-url (concat "https://github.com/org/repo/blob/" + revision))) + (should (equal (ai-code--doc-github-source-url) source-url)) + (cl-letf (((symbol-function 'read-string) + (lambda (&rest _) "github"))) + (should (eq (ai-code--read-document-link-style) 'github))) + (let ((prompt (ai-code--org-link-instruction "a/b/doc.org" 'github))) + (should (string-match-p (regexp-quote (concat source-url "/")) + prompt)) + (should-not (string-match-p "/blob/HEAD/" prompt)) + (should (string-match-p "untracked, ignored" prompt))) + ;; New document files must not disable links to committed code. + (with-temp-file "doc.org" (insert "Draft document\n")) + (with-temp-file "generated.txt" (insert "Generated output\n")) + (should (equal (ai-code--doc-github-source-url) source-url)) + (git "checkout" "--detach" "-q") + (should (equal (ai-code--doc-github-source-url) source-url)) + ;; Both unstaged and staged edits invalidate committed line numbers. + (with-temp-file "source.txt" (insert "Local definition\n")) + (should-not (ai-code--doc-github-source-url)) + (git "add" "source.txt") + (should-not (ai-code--doc-github-source-url)) + (let ((prompt (ai-code--org-link-instruction "a/b/doc.org" 'github))) + (should-not (string-match-p "https://github.com" prompt)) + (should (string-match-p + (regexp-quote "[[file:../../path/to/file::symbol]") + prompt)))))) + (delete-directory repo t)))) + +(ert-deftest test-ai-code-doc--github-source-url-handles-git-failure () + "An unavailable Git command must leave local document links usable." + (cl-letf (((symbol-function 'ai-code--doc-github-repo-url) + (lambda () "https://github.com/org/repo")) + ((symbol-function 'magit-git-string) + (lambda (&rest _) (error "Git unavailable")))) + (should-not (ai-code--doc-github-source-url)) + (should (string-match-p + (regexp-quote "[[file:path/to/file::symbol]") + (ai-code--org-link-instruction "doc.org" 'github))))) + (provide 'test_ai-code-doc) ;;; test_ai-code-doc.el ends here ;;; test_ai-code-doc.el ends here diff --git a/test/test_ai-code-github.el b/test/test_ai-code-github.el index 751f2e0c..597cd420 100644 --- a/test/test_ai-code-github.el +++ b/test/test_ai-code-github.el @@ -693,6 +693,24 @@ branch as the PR base." (should (string-match-p "Class definition: class GreetingService:" captured-prompt)) (should (string-match-p "Function definition: defun hello-world ()" captured-prompt)))) +(ert-deftest test-ai-code-github--get-git-web-repo-url-supports-remote-formats () + "Normalize supported remotes without treating SSH ports as path segments." + (dolist (entry '(("https://github.com/org/repo.git" . "https://github.com/org/repo") + ("https://gitlab.example:8443/org/repo" . "https://gitlab.example:8443/org/repo") + ("git@github.com:org/repo.git" . "https://github.com/org/repo") + ("ssh://git@github.com/org/repo.git" . "https://github.com/org/repo") + ("ssh://git@github.com:22/org/repo.git" . "https://github.com/org/repo") + ("ssh://github.com/org/repo" . "https://github.com/org/repo") + ("ssh://git@gitlab.example:2222/group/repo.git" . "https://gitlab.example/group/repo") + ("ssh://git@github.com:invalid/org/repo.git" . nil) + ("/tmp/git@github.com:org/repo.git" . nil) + ("/tmp/https://github.com/org/repo.git" . nil) + ("" . nil) + (nil . nil))) + (cl-letf (((symbol-function 'magit-git-string) + (lambda (&rest _) (car entry)))) + (should (equal (ai-code--get-git-web-repo-url) (cdr entry)))))) + (provide 'test_ai-code-github) ;;; test_ai-code-github.el ends here