A context management method and system for an ai programming assistant based on a task state machine

CN123014223APending Publication Date: 2026-10-30ZHONGBO INFORMATION TECH RES INST CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611501916.4
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-09-24
Publication Date
2026-10-30

AI Technical Summary

Technical Problem

[0005]上述方案的共同问题在于:管理的对象是“对话内容”,即文本、摘要、向量或记忆,而不是“任务执行状态”

Benefits of technology

(1)任务状态机构建与待执行步骤生成:通过显式指令和工具调用结果识别任务,任务节点包含待执行步骤字段(pending_steps),该字段在任务创建或状态流转为进行中时,基于任务描述及依赖的已完成任务的产出自动生成,作为连续性验证中关键词覆盖率比对的基准;

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123014223A_ABST
    Figure CN123014223A_ABST
Patent Text Reader

Abstract

The application discloses a kind of context management method and system of AI programming assistant based on task state machine, including task state mechanism construction, task entity is divided from user sentence by word segmentation and part-of-speech tagging and is normalized, forms the task node including task state, dependency relationship, output, key decision and to-be-executed step, and determines current focus task;Selective arrangement based on focus task path, retain focus task path and dependent output, compress non-path task;Task continuity inference verification, after arrangement context is input LLM model to infer current task, next operation and required output, with task state machine carries out three comparisons of semantic similarity, keyword coverage, output existence, does not pass through then returns to re-verification, exceeds iteration upper limit then retains original context;Next planning and input check based on task state machine.The application makes compression strategy and current task state coupling, guarantees the continuity of compressed task.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of artificial intelligence-assisted software development, specifically relating to a context management method and system for an AI programming assistant based on a task state machine. Background Technology

[0002] When AI programming assistants help users complete development tasks, they need to continuously provide context, such as historical dialogues and tool call results, to a large language model. As the conversation progresses, the length of the context gradually approaches the upper limit of the model window, necessitating the compression and organization of historical content. How to preserve the key information needed for the current task while compressing this information is the main challenge faced by these tools. Existing context management solutions mainly fall into the following categories: (1) The dcp plugin in the OpenCode ecosystem; dcp (Dynamic Context Pruning) allows the model to autonomously decide when to compress via the compress tool. It supports compressing continuous dialogue spans into technical summaries (range mode) or independently compressing single messages (message mode). When new and old summaries overlap, multi-level nested summaries are formed, and it has automatic cleanup strategies such as deduplication of tool calls and cleanup of erroneous calls. Its managed object is dialogue text: which content to compress is determined by the model according to the text span, and the compressed content is directly sent to the model; it does not recognize the execution status of development tasks, nor does it disclose a verification mechanism for whether the compressed task can be correctly continued.

[0003] (2) SuperMemory plugin; SuperMemory triggers intelligent compression when the context length reaches a fixed proportion (default 80%) of the model's maximum window. Combined with built-in or custom keyword pattern detection, it stores important information in an external memory and injects it when needed. Its triggering and compression are both based on fixed thresholds and keyword matching. It does not have the ability to understand the structure of the current development task, and after compression, it is also impossible to verify whether the task can be correctly continued.

[0004] (3) Memory-based solutions such as hindsight and mem0; hindsight injects the historical memory of semantic retrieval into the compressed context during the context compression stage through conversation lifecycle hooks; mem0 extracts entities, relationships, and user preferences from cross-conversation dialogues to construct a user-level memory graph. These solutions focus on memory retention, retrieval, and persistence of user preferences, but do not have the concept of task execution state, and do not verify whether the model can correctly infer the next operation based on the current task state after injection or retrieval.

[0005] The common problem with the above solutions is that they manage "dialogue content," i.e., text, summaries, vectors, or memories, rather than "task execution status." In the common use cases of AI programming assistants, user interaction with AI is essentially a collaborative effort to complete a series of development tasks (such as "building a user system," which includes "designing the database → writing the login interface → writing the registration interface → writing tests").

[0006] Managing dialogue content leads to four shortcomings in the existing solution: First, it fails to recognize the completion status of tasks, storing a large amount of dialogue transcripts without knowing where it is currently. Second, it does not proactively plan the next step based on the overall task structure, only responding passively. Third, after compressing or injecting memories, it does not verify whether the AI ​​can still correctly infer what to do next based on the current state after being put back in; once key information is compressed, the task is immediately interrupted. Fourth, the compression strategy is irrelevant to the task, deleting content by time or length, which may delete the key context required for the "currently being done task" while retaining irrelevant details that have already been completed. Summary of the Invention

[0007] To address the aforementioned issues, the present invention aims to provide a context management method and system for an AI programming assistant based on a task state machine. This method can transform scattered dialogues into a task execution state diagram, coupling the compression strategy with the current task state. After context compression, the method verifies whether the AI ​​can still correctly continue the current task through task continuity inference. Based on the dependencies of the task state machine, the method performs the next operation planning and input parameter compatibility check.

[0008] The specific technical solution for achieving the objective of this invention is as follows: A context management method for an AI programming assistant based on a task state machine includes the following steps: Step 1: Construct the task state machine; Step 2: Selective organization based on the focus task path; Step 3: Verify the continuity of the task; Step 4: Next step planning and input parameter check based on the task state machine.

[0009] This solution also provides a context management system for an AI programming assistant based on a task state machine, including the following modules: State machine construction module: used for constructing task state machines; Selective Sorting Module: Used for selective sorting based on the focus task path; Inference and Verification Module: Used for inference and verification of task continuity; Next Step Planning and Checking Module: Used for next step planning and input parameter checking based on the task state machine.

[0010] Compared with the prior art, the beneficial effects of the present invention are as follows: (1) Task state machine construction and generation of pending steps: Tasks are identified by explicit instructions and tool call results. The task node contains a pending steps field (pending_steps). This field is automatically generated based on the task description and the output of the completed tasks it depends on when the task is created or the state transitions to in progress. It serves as the benchmark for keyword coverage comparison in continuity verification. (2) Selective sorting strategy for focus task paths: recursively query the parent tasks of focus tasks until the root task to form the focus task path, retain all node information and dependent outputs on the path, compress non-path completed tasks into a summary, and discard non-path pending tasks, which is different from the existing technology of compressing by text span or fixed threshold. (3) Three joint comparisons for task continuity inference verification: semantic similarity comparison (cosine similarity between the inferred current task and the description of the focus task ≥ 0.8), keyword coverage comparison (coverage between the inferred next operation and the steps to be executed in the focus task ≥ 60%), and output existence check (all inferred required outputs exist in the recorded outputs). The three joint verifications verify whether the compressed context still supports correct task inference. Semantic similarity is calculated by encoding pre-trained sentence embedding models that are independent of the inference model, and then calculating cosine similarity. Keyword coverage is calculated by using the verbs and nouns extracted in the steps to be executed as the benchmark keyword set, and then calculating the ratio of the number of benchmark keywords hit in the next operation to the total number of the benchmark set. (4) Two rounds of correction and downgrading for failed verification: If any comparison item fails, the missing information is supplemented from the local storage and the system is reorganized and re-verified, with a maximum of two iterations; if it still fails after more than two iterations, the original context is retained; if the verification model outputs abnormalities twice in a row, the verification step is skipped. (5) Next step planning and input parameter compatibility check based on task state machine: After verification, the next step is actively planned based on task dependency relationship (dependency priority, subtask expansion, historical habit assistance); before execution, the existence of output, decision consistency and scope validity of input parameters are checked. The decision consistency check is determined by extracting positive keywords and querying the preset conflict dictionary to obtain conflict keywords.

[0011] The present invention will be further described below with reference to specific embodiments. Attached Figure Description

[0012] Figure 1 This is a schematic diagram of the context management method for an AI programming assistant based on a task state machine, provided in an embodiment of the present invention.

[0013] Figure 2This is a schematic diagram of the task state machine data structure in an embodiment of the present invention.

[0014] Figure 3 This is a flowchart illustrating the closed-loop process for task continuity inference and verification in an embodiment of the present invention. Detailed Implementation

[0015] Example

[0016] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. The described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0017] As indicated in this application and claims, unless the context clearly indicates otherwise, the words "a," "an," "an," and / or "the" do not specifically refer to the singular and may also include the plural. Generally speaking, the terms "comprising" and "including" only indicate the inclusion of explicitly identified steps and elements, which do not constitute an exclusive list, and the method or apparatus may also include other steps or elements.

[0018] Unless otherwise specifically stated, the relative arrangement, numerical expressions, and values ​​of the components and steps described in these embodiments do not limit the scope of this application. It should also be understood that, for ease of description, the dimensions of the various parts shown in the drawings are not drawn to actual scale. Techniques, methods, and devices known to those skilled in the art may not be discussed in detail, but where appropriate, such techniques, methods, and devices should be considered part of the specification. In all examples shown and discussed herein, any specific values ​​should be interpreted as merely exemplary and not as limitations. Therefore, other examples of exemplary embodiments may have different values. It should be noted that similar reference numerals and letters in the following drawings denote similar items; therefore, once an item is defined in one drawing, it need not be further discussed in subsequent drawings.

[0019] First, a unified explanation of some of the terms used in this plan will be provided: Task State Machine (TSM): A directed graph structure consisting of task nodes, inter-task dependency edges, and task state attributes, used to represent the task execution state in an AI programming assistant session.

[0020] Focus Task: The task node that is currently in the "doing" state and has been most recently activated, representing the main work that the AI ​​is currently performing.

[0021] Task path: Starting from the focus task node, recursively trace upwards through the parent task nodes to the root task to form a task chain.

[0022] Task continuity inference verification: Input the compressed context into the LLM model, require the model to infer the current task and the next operation, and compare the inference results with the task state machine to verify the task continuity of the compressed context.

[0023] Trigger threshold: When the context length reaches this threshold, the cleanup is triggered. In this embodiment, it is set to a fixed proportion of the model's maximum context window.

[0024] Combination Figure 1 A context management method for an AI programming assistant based on a task state machine includes the following steps: Step 1, Combining Figure 2 The Task State Machine (TSM) is constructed by binding all aspects of context management (compression triggering, compression strategy, recovery verification, and next step planning) to the Task State Machine. Step 1-1, Task Identification and State Transition: The user's statement is segmented and tagged with part-of-speech tags using a general Chinese word segmentation and part-of-speech tagging tool. After matching the trigger word from the preset "task trigger verb list", the continuous noun phrases / verb-object phrases following it are used as task entities for segmentation. The segmented task entities are normalized and written into the task description field of the task node to form the task node. The task node includes task ID, task description, task status, parent task information, dependent task ID, task output, key decisions involved in the task, list of steps to be executed, and focus sorting value; This embodiment provides a task node structure: interface TaskNode { id: string; description: string; / / Task description, such as "Write a login interface" status: 'todo' | 'doing' | 'done' | 'pending'; parent_id: string | null; / / Parent task (supports nesting) dependencies: string[]; / / IDs of other dependent tasks outputs: string[]; / / Task outputs (such as file paths, table structure definitions) key_decisions: string[]; / / Key decisions involved in the task pending_steps: string[]; / / List of steps to be executed, used for continuous verification and comparison focus_order: number; / / Focus order value, the larger the value, the newer the task, updated to the current maximum value plus one each time it is activated created_at: number; completed_at: number | null;}; The task status includes to-do, doing, done, and pending. The pending_steps list of task nodes is generated and stored in the pending_steps field when a task node is created or its status is "doing". This list is based on the task description and the task outputs of task nodes with a "done" status in their dependent task IDs. Specifically, it includes: Derivation based on dependency outputs: If the outputs of a task node's dependent completed task include a specific file or table structure, then the pending_steps list should include the operation steps for that output; for example, if the outputs of the dependent task record the users table (id, username, email), and the focus task is "write registration interface", then the pending steps are generated such as "insert user record into users table" and "create registration route". Task Description Extraction: The verb and noun components of the task description are extracted and rewritten according to a preset "verb-object → operation step" rule to generate corresponding operation steps. For example, for "Write a registration interface," the steps "Create a registration route" and "Implement a registration controller" are generated. Combined with the key_decisions of dependent tasks (such as "User authentication uses JWT"), the step "Add JWT verification" is added, ultimately generating ["Create registration route", "Implement registration controller", "Add JWT verification"]. This rewriting rule is configurable.

[0025] Update timing: When the output of a task that depends on another task changes or the user provides additional information about the scope of the task, the system regenerates the pending steps list (pending_steps) and overwrites the old value. The pending_steps serve as the benchmark for keyword coverage comparison in subsequent continuous inference verification (step 3), ensuring that the comparison benchmark for the verification phase has been generated before verification is triggered.

[0026] More specifically, this solution's system monitors interactions through chat.message and tool.execute.after hooks, and identifies tasks based on explicit commands and tool call results.

[0027] Specific task identification rules include: (1) Task creation and status transition based on explicit user instructions: If the user input includes expressions such as "do X", "implement X", "write X", "next X", etc., extract X as a new task and set the task status to doing; if the user input includes "X is done" or "X is ready", the task status of task X will be transitioned to done; if the user input includes "don't do X yet" or "X is paused", the task status of task X will be transitioned to pending. (2) Active task confirmation based on tool call results: If the AI ​​executes a tool call related to task X (such as writing a file or executing a command), confirm that task X is an active task, that is, maintain the task status of task X as "doing", and use it as the activation basis for the focus task determination in steps 1-3. (3) Exclusion of query / debugging statements: If the user inputs query or debugging statements such as "Let's see how X is written" or "How does X report an error", it is determined that it does not constitute a new task and no new task node is created; the exclusion of such query / debugging statements is given priority in the task identification rules.

[0028] In the above rules, X represents the task entity, which is the task object identified and segmented from the user statement or tool call result. This embodiment uses a general Chinese word segmentation and part-of-speech tagging tool, such as jieba or HanLP, to segment and tag the user statement. After matching the trigger word from the preset "task trigger verb list" (such as "do / implement / write / create / write", which can be configured), the continuous noun phrase / verb-object phrase following it is segmented as the task entity X (e.g., X="login interface" is segmented from "help me write login interface").

[0029] In multilingual scenarios, it can be replaced with a general NLP pipeline for the corresponding language (e.g., spaCy for English).

[0030] The segmented task entities can be further normalized, for example: mapping synonyms / near-synonyms (such as "login" and "login") to standardized expressions based on public synonym resources; completing abbreviated expressions by combining the most recently completed "doing" task in the task state machine (such as completing "continue writing tests" to "testing the login interface"); and using a rule mapping table to unify abbreviations / aliases.

[0031] Step 1-2: Identify task dependency edges: If a user proposes task node B immediately after completing task node A, and task node B uses the output of task node A (e.g., "The database design is complete, now write the interface"), then a dependency edge A→B is established. If the AI ​​programming assistant reads the file produced by task node A when executing task node B, then a dependency edge A→B is established. After establishing the dependency edge from task node A to B, check whether task node B has read the file or field in the task output of task node A. If it has not read it, mark it as a "weak dependency" instead of a strong dependency. In the subsequent selective sorting process based on the focus task path in step 2, the dependency node marked as a "weak dependency" is not forcibly retained, and is only included in the context when the focus task explicitly references it.

[0032] Steps 1-3: Determine the current focus task: The current focus task is the most recently activated task node among those whose task status is "doing". If there are multiple task nodes with a status of "completing," the one most recently explicitly mentioned by the user shall prevail. When there are multiple task nodes with a "completing" status and the user's current statement does not explicitly mention any task node, the following rules will be used to assist in the determination: Prioritize the task nodes involved in the most recent round of dialogue; if the most recent round involves multiple task nodes, select the task with the highest focus ranking value as the current focus task. This determination result is logged for later review.

[0033] This section provides a detailed explanation of "activation" and "explicit mention": Activation determination: When the task entity extraction process successfully extracts a task entity from the user statement or tool call result, and creates or transfers the task node accordingly, the task is determined to be "activated". At the same time, the focus_order field of the task node is refreshed to the current maximum value plus one (that is, it is updated to the latest sort value every time it is activated).

[0034] Explicit mention criteria: This refers to the situation where a specific task entity can be extracted from the user's current statement according to the extraction process (such as "registration interface" in "write registration interface"). If the user's statement only contains generic pronouns or conjunctive phrases (such as "keep doing", "continue", "it / this", etc., which cannot extract a task entity), then it does not fall under "explicit mention", and the focus task remains unchanged from the previous round of criteria.

[0035] In this embodiment, the final generated task state machine is stored in a local SQLite, including a task table (the fields correspond one-to-one with the task node structure mentioned above), a dependency edge table (task_deps) (recording the dependency relationship between task IDs), and a task state transition log table (task_transitions) (recording the source task from_task, target task to_task, transition type and time for each state transition, for use in step 4 for statistics and anomaly tracing).

[0036] Step 2: Selective reorganization based on the path of the focus task. Unlike fixed thresholds (such as 80% of supermemory) or model-auto-judgment (such as dcp), the compression strategy of this invention is bound to the path of the current focus task. Step 2-1: Preserve the path of the focus task: Recursively query the parent task information of the current focus task up to the root task to form the focus task path, and retain the task description, task status, task output and key decisions of all task nodes on the path. Step 2-2, Dependency Path Preservation: Query the dependency edges of the current focus task and preserve the outputs and key decisions of the completed task nodes that are depended upon. Steps 2-3: Retain the original text of the three most recent rounds of dialogue; Steps 2-4: Non-path task compression: Compress task nodes with a completed status ("done") that are not on the path dependent on the focus task into a one-sentence summary (keeping only the description and outputs list). For example, this can be achieved using either of the following methods: (a) Call the local code model or the main dialogue model, using the fixed prompt "Please summarize the description and outputs of the following task in one sentence" and concatenating the description and outputs of the task to generate the summary; (b) Do not call the model, but directly use template strings to concatenate (e.g., "[task]"+description+", output: "+outputs.join("、")); Steps 2-5: Pause pending task processing: Task nodes with a pending status and not on the dependency path are not retained in the context sent to the LLM model, but only in SQLite for later resumption.

[0037] Compared to existing technologies that use DCP to compress based on text span without distinguishing tasks, this invention compresses based on task path, retaining the complete task chain related to the current focus task and discarding irrelevant completed tasks.

[0038] Step 3, Combining Figure 3 Task continuity inference verification. This invention verifies recovery quality by having AI infer the next step based on the compressed context, specifically including: Step 3-1: Construct the inference request: Using a fixed prompt template, including system instructions, a condensed context, and a specified JSON output format, the LLM model is required to infer the current task description, the next operation, and the completed outputs required to execute the next step based on the condensed context, and output the inference results in JSON format. For example, in this embodiment:

[0039] [System Command]

[0040] You are a project status analysis assistant. Please answer three questions based on the following project background and current progress:

[0041] 1. What is the current task of this project? (Describe it in one sentence)

[0042] 2. What should be the next step in this task? (Describe it in one sentence)

[0043] 3. Which completed deliverables should be referenced before proceeding to the next step? (List the deliverable names)

[0044] [Context]

[0045] {Compressed Context}

[0046] Please strictly adhere to the following JSON format for output:

[0047] {

[0048] "current_task": "Description of the current task",

[0049] "next_step": "Next step",

[0050] "required_outputs": ["Output 1", "Output 2"]

[0051] }

[0052] Step 3-2: Obtain the inference results: The selectively processed context from step 2 is input into the LLM model to obtain JSON output; for example, inference can be performed using a large local code model of level 7B~14B (such as Qwen2.5-Coder-7B-Instruct, DeepSeek-Coder-V2-Lite-Instruct, or similar models). Such models can be deployed with low latency on consumer-grade GPUs, meeting real-time verification requirements.

[0053] If two consecutive outputs contain JSON format errors or output names that are not in any task outputs, the task continuity inference verification model is deemed abnormal. At this point, skip the verification step, retain the current compression result, and record the exception log for later troubleshooting or replacement of the verification model; Step 3-3: Compare the inference results from Step 3-2 with the task state machine, as shown in Table 1: Table 1. Comparison Items for Task Continuity Inference Verification

[0054] Current task The semantic similarity between the inference result current_task and the focus task description Cosine similarity ≥ 0.8 (preferred range 0.75~0.85) Next steps Keyword coverage of the inference result next_step and the focus task pending_steps Coverage rate ≥ 60% (preferred range 55%~65%) Required output Check whether each output listed in the inference results required_outputs exists in the task output of the focus task and the task output of each task node that the focus task depends on. It is considered passed if all listed outputs exist.

[0055] The specific calculation method for the three comparisons is as follows: Semantic similarity calculation: A pre-trained sentence embedding model (such as the general sentence encoding model of the SBERT series) is used to encode the inference result current_task and the focus task description into vectors respectively. The cosine similarity between the two is calculated. When the cosine similarity is greater than the set threshold, it is considered to pass. This embedding model and the local code model used for inference in step 3-2 are two independent components. The embedding model is only used for short text vectorization and does not perform inference tasks. It is small in size, fast inference, and can be deployed independently. Keyword coverage calculation: Using the keyword set K_base of each step in the pending_steps list as the baseline (extracting verbs and nouns from each step as keywords, and forming the baseline set K_base after deduplication), the number of baseline keywords hit by the inference result next_step is counted, and the coverage is calculated according to the following formula. When the coverage is higher than the set threshold, it is considered to have passed: Coverage = |next_step set of keywords hit ∩ K_base| / |K_base|; For example, if pending_steps is ["Create registration route", "Implement registration controller", "Add JWT verification"], extract verb and noun keywords from each step, and after deduplication, form a base keyword set K_base = {create, register, route, implement, controller, add, JWT, verification}, which has 8 keywords. If next_step is "Create registration route and controller, JWT verification required", the matched base keywords are {create, register, route, controller, JWT, verification} (6 keywords in total, "required" is not in the base set), and the coverage is 6 / 8 = 75% ≥ 60% → pass.

[0056] Required outputs: Check whether each output listed in the inference result required_outputs exists in the task outputs of the focus task and the task outputs of each task node that the focus task depends on. If all listed outputs exist, it is considered to pass. If all three items above pass, the task continuity inference verification is considered successful; if any one item fails, the task continuity inference verification is considered unsuccessful.

[0057] When the task continuity inference verification fails, locate the missing information that caused the failure, and add the missing task nodes or outputs to the end of the context. Then return to step 2 to re-execute selective sorting and inference verification. Iterate a maximum of two times. If it still fails after two iterations, retain the original context.

[0058] If the validation requirements are still not met after two rounds of patching iterations, and the original context exceeds the model's maximum window limit: Prioritize retaining all nodes corresponding to the focus task path (recursive parent chain, outputs and key decisions dependent on completed done nodes); Secondly, retain the original dialogue from the most recent 3 rounds; The remaining non-critical context is compressed into the window using a hierarchical summary method to avoid request failure due to context exceeding limits.

[0059] If the continuous verification model outputs incorrect format or obviously illusory content twice in a row (such as generating a non-existent output file out of thin air), the verification step is skipped directly, and the current compression result is retained to avoid blocking the normal process due to verification model failure.

[0060] In contrast, existing technologies inject memory into hindsight without performing any checks, and then send it directly to the LLM after DCP compression; this invention directly verifies "whether the compressed context still supports correct task reasoning" through task continuity inference, rather than simple string matching or data integrity checks.

[0061] Step 4: Next step planning and input parameter check based on the task state machine: Step 4-1: Actively plan the next step based on the task state machine. The planning rules include: Dependency priority rule: Prioritize checking whether the task output of the task node with the status of "done" in the dependent task ID of the focus task has been used; Subtask unfolding rules: If the focus task has subtasks, that is, the parent task information of other task nodes points to the focus task (parent_id points to it), the subtasks are arranged in order of task status todo taking precedence over doing, as candidate order for the next step of planning; Historical habit auxiliary rules: Query the task transition log table `task_transitions` in SQLite to count the most frequently executed next task type from the current task type, as a suggestion; where "task type" is determined based on keyword extraction from the task description or a preset task type classification rule; the statistical method is to group and count records in the `task_transitions` table where the source task `from_task` is the current task type, and take the most frequent one as the suggestion; when historical records are insufficient, only the above dependency priority and subtask expansion rules are relied upon. Step 4-2: Before proceeding to the next task, check the compatibility of the outputs recorded in the task state machine. The check items include output existence, decision consistency, and scope validity, as shown in Table 2: Table 2 Input Parameter Compatibility Check Items

[0062] Output Existence Does the file / table / field referenced by the input parameter exist in the outputs of focus_task or its dependent tasks? Query the outputs field of the tasks table Decision consistency Does the input parameter violate the technical decisions recorded in key_decisions? Keyword matching + negation rule detection (see explanation below) Scope validity Are the parameter values ​​within a reasonable range? rule base

[0063] The existence of outputs refers to checking whether the file / table / field referenced by the input parameters exists in the task output of the focus task or its dependent tasks. Decision consistency means checking whether the input parameters violate the recorded technical decisions; Range validity means checking whether the parameter value is within a reasonable range.

[0064] The decision consistency is determined by the following rules to determine whether the input parameters violate the recorded technical decisions: Positive decision matching: For decisions of the type "adopt solution X", check whether the input parameters contain keywords of alternative solutions that conflict with X. If they do, it is determined that decision consistency is violated. For example, if key_decisions records "adopt JWT solution", the system extracts the positive keyword {JWT} from the text and queries the preset authentication solution conflict dictionary to obtain conflict keywords {Session, Cookie, Basic Auth}. If the authentication method field in the input parameters contains conflict keywords, it is determined that decision consistency is violated.

[0065] Negative constraint detection: For decisions of the type "prohibit / do not X", extract the prohibited target and check whether the input parameter touches the target. If so, it is determined to be a violation of decision consistency. For example, if key_decisions records "prohibit modifying config.json", and the file path of the input parameter contains config.json, it is determined to be a violation.

[0066] Construction of the conflict dictionary and rule base: (1) Manual pre-configuration: The developer writes an initial knowledge base based on the target technology field (such as Web development, mobile terminal) during deployment. For example, the authentication scheme conflict dictionary pre-configures conflict mappings such as {JWT: [Session, Cookie, Basic Auth]}. (2) Expand based on historical output statistics: Scan the task_transitions table and the outputs / key_decisions of historical task nodes, count the frequently co-occurring technical terms and decision pairs, and automatically expand the conflict dictionary and classification rules; (3) Loading based on domain configuration files: Organized in the form of structured configuration files such as JSON / YAML, loaded into memory when the system starts, and supports hot updates at runtime.

[0067] Existing technologies lack input parameter checks, while the input parameter checks of this invention are based on the outputs and decisions already recorded in the task state machine, rather than a simple document scan.

[0068] The following calibration method is based on the OpenCode 1.18.x environment. For continuous inference verification, a large local code model of level 7B to 14B (such as Qwen2.5-Coder-7B-Instruct, DeepSeek-Coder-V2-Lite-Instruct and other similar models) can be used.

[0069] (1) The logic for determining the semantic similarity threshold: A suitable threshold can be determined through a small sample size of no more than 50 groups: select conversation samples covering typical programming scenarios such as single task, dual parallel task, three-level dependency task, and temporary requirement change, and test the performance of semantic similarity threshold in the range of 0.7 to 0.9, and statistically analyze two core indicators: False positive rate: Misjudging a task that can actually be continued as one that cannot be continued leads to unnecessary context recovery and additional token consumption; Missed detection rate: Misclassifying tasks that are actually unsuccessful as available, leading to task interruption and requiring the user to re-enter the information.

[0070] Standard calibration indicates that the suitable range for semantic similarity is 0.75 to 0.85, with approximately 0.8 being the preferred value. This range achieves a good balance between task continuation accuracy and token consumption. When switching to a code model of the same scale, fine-tuning the threshold within ±0.05 is sufficient for adaptation.

[0071] (2) Calibrating logic for keyword coverage threshold: For the keyword coverage threshold in the next step, performance within the 50%~80% range can be tested by simulating compression scenarios of tasks with varying complexity. The focus should be on statistically analyzing the missed detection rate of key outputs (the probability of missing explicitly defined user constraints and core dependencies). Conventional calibration results indicate that the suitable range is 55%~65%, with approximately 60% being the optimal value. This range effectively filters out non-critical redundant keywords while keeping the missed detection rate of user constraints and core dependencies within an acceptable range. For different programming languages ​​(such as Java, C++, front-end frameworks, etc.), adaptation is achieved simply by adjusting the keyword dictionary for the corresponding language; recalibrating the threshold is unnecessary.

[0072] (3) Logic for determining the number of iterations and the most recent dialogue round: To determine the number of iterations for recovery and the number of rounds retained from the most recent original dialogue, tests can be conducted by simulating compressed scenarios with different context lengths: Number of iterations: The success rate of repair in 1 round of iteration is low and cannot cover the need to complete most missing information; 2 rounds of iteration can cover most repairable missing scenarios with low additional token consumption; the improvement in the success rate of repair in ≥3 rounds of iteration is not significant, but the token consumption increases significantly. Therefore, setting a maximum of 2 rounds of iteration is the better choice.

[0073] Recent conversation retention rounds: Retaining 1 round is prone to losing the user's previous temporary constraints (such as "prohibit modification of config.json"); retaining 2 rounds still has a high rate of missing key constraints; retaining 3 rounds can keep the rate of missing key constraints at a low level with only a small increase in token consumption; retaining 4 rounds or more will significantly increase token consumption but the benefits are limited, so it is preferable to retain the most recent 3 rounds of original conversation.

[0074] The following section provides a further explanation of this solution in the context of a specific deployment scenario. This system is deployed as an OpenCode 1.18.x plugin and developed using the TypeScript / JavaScript technology stack (task recognition is based on rule matching and Hook event monitoring; the task state machine is stored in a local SQLite; continuous inference verification uses a standard LLM inference interface and fixed prompt word templates, and the verification model can be a large local code model of 7B~14B level). The database uses a local SQLite and is integrated with the OpenCode plugin system.

[0075] (1) Task state mechanism construction: The user is developing a web application using the OpenCode 1.18.x plugin and is implementing a user authentication module. The continuous authentication model is deployed locally using Qwen2.5-Coder-7B-Instruct. In round 5, the user says, "Help me build a user system, starting with database design." The system identifies task t1: "Design database," with a status of "doing," no parent task, and no dependencies. In round 8, the user says, "The user table has id, username, and email; the role table has id and name. Now write the login interface." The system updates the status of t1 to "done," records outputs ["users table (id, username, email)", "roles table (id, name)"], and key_decisions ["User authentication uses the JWT scheme"]. Simultaneously, it identifies task t2: "Write login interface," with a status of "doing" and a dependency pointing to t1 (depending on the completion of database design). In round 12, the user says, "Login is written, now write the registration interface, which also needs JWT verification." The system updates the t2 state to done, and records outputs ["src / routes / auth.js", "src / controllers / authController.js"]. It identifies task t3: "Write the registration interface", with the state "doing", and its dependencies pointing to t1 and t2. Based on the description of t3 and the outputs of the completed tasks it depends on, it generates pending_steps: ["Create registration route", "Implement registration controller", "Add JWT verification"].

[0076] At this point, the task state machine is as follows: Focus task t3 (writing the registration interface, doing); Dependency chain t1 (done) → t2 (done) → t3 (doing).

[0077] (2) Selective organization of task paths: Context length reaches the threshold, triggering cleanup. Retain: Information on each task node along the focus path t3 (doing) → t2 (done) → t1 (done); the dependent outputs of t3, i.e., the outputs of t1 (user table fields) and the key_decisions of t2 (JWT solution); the most recent three rounds of dialogue (details regarding the registration interface). Compress: The detailed design process of t1 (completed detailed dialogue on a non-focus path) is compressed into a summary: "Database design completed, users table fields id / username / email, roles table fields id / name"; the detailed coding process of t2 is compressed into a summary: "Login interface completed, located in auth.js and authController.js". Discard: Redundant dialogues already recorded as key_decisions in early technology selection discussions; user-mentioned "potential future permission management" (pending task, not on the current dependency path).

[0078] (3) Validation of task continuity inference: The system constructs an inference request (using the prompt word template from step 3-1), fills in the organized context, and verifies the model output:

[0079] {

[0080] "current_task": "Write the user registration interface",

[0081] "next_step": "Create registered routes and controllers, JWT authentication required",

[0082] "required_outputs": ["users table fields", "auth.js"]

[0083] }

[0084] Comparison: The semantic similarity between the current task "Write the user registration interface" and the description "Write the registration interface" in t3 is 0.92 ≥ 0.8, passing; the next operation hits 6 base keywords {create, register, route, controller, JWT, verification} (8 in K_base), with a coverage of 6 / 8 = 75% ≥ 60%, passing; the required outputs ["users table fields", "auth.js"] all exist in the outputs of t1 and t2, passing. All three comparisons passed, and the verification passed.

[0085] As a comparison, if the output of t1 is accidentally lost during the processing (the users table field is not retained), the validation model will output:

[0086] {

[0087] "current_task": "Write the user registration interface",

[0088] "next_step": "We need to first understand what fields the user table has",

[0089] "required_outputs": ["users table fields"]

[0090] }

[0091] At this point, the next step did not hit any benchmark keywords, and the coverage rate = 0 / 8 = 0% < 60%, so it failed; the required output "users table fields" are not in the reorganized context, so it also failed. Failure handling: 1. Locate the missing: the users table fields in the output of t1; 2. Supplement the output of t1 from SQLite to the end of the context; 3. Reorganize (prioritize retaining the supplemented content); 4. Revalidate, and it passed.

[0092] (4) Next steps in planning and data entry inspection: Planning: Based on the dependencies of t3, t1 and t2 are complete, and the outputs are confirmed to be ready; t3 has no subtasks, and the next step is to execute coding; Historical practice: The transition from "writing the login interface" to "writing the registration interface" is common and carries no additional risk. Input parameter check: The AI ​​is preparing to write to src / routes / auth.js to add a registration route, with input parameters {path: " / register", method:"POST"}; Output existence: auth.js is already recorded in the outputs of t2 and exists; Decision consistency: t1's key_decisions record "user authentication uses the JWT scheme", and the authentication method field in the input parameters does not contain {Session, Cookie, Basic Auth} from the conflict dictionary, consistent with the JWT scheme; Scope validity: the method is POST, which is reasonable. Input parameter check passed, and the AI ​​executes the operation.

[0093] (5) Parallel tasks and scenarios of misidentification of dependency edges: Parallel Tasks: When a user is in the 15th round of task t3 (writing the registration interface, doing), they suddenly say, "First, take a look at the API documentation generation script; there's a problem." The system recognizes this as a query / debugging instruction and does not create a new task node. If the user subsequently says, "Help me modify the API documentation script," the system recognizes a new task t4: "Modify the API documentation script," in the doing state. At this point, there are two parallel tasks, t3 (doing) and t4 (doing). According to the set rules, t4, which the user most recently explicitly mentioned, becomes the focus task. During compression, the focus path of t4 (if t4 is independent and has no dependencies) and the most recent three rounds of dialogue are preserved. t3, as a non-focus doing task, retains its outputs and key_decisions but not its detailed dialogue. The verification model infers that the current task should be related to the description of t4, comparing it with the description of the focus task t4. If they match, the process continues.

[0094] Dependency edge misidentification: After the user says "write the login interface" in round 8, in round 9 they say "by the way, help me check the Redis connection configuration". The system may mistakenly identify "check Redis configuration" as a task that depends on t1 (database design). According to the preset rules, check whether the task actually reads t1's outputs (fields of the users table / roles table). If it does not read them, mark it as "weak dependency". Weak dependency nodes are not forcibly retained during subsequent compression to avoid irrelevant context occupying context space.

[0095] This solution also provides a context management system for an AI programming assistant based on a task state machine, including the following modules: State machine construction module: used for constructing task state machines; Selective Sorting Module: Used for selective sorting based on the focus task path; Inference and Verification Module: Used for inference and verification of task continuity; Next Step Planning and Checking Module: Used for next step planning and input parameter checking based on the task state machine.

[0096] The embodiments described above are merely illustrative of several implementation methods of this application, and while the descriptions are relatively specific and detailed, they should not be construed as limiting the scope of the invention patent. It should be noted that those skilled in the art can make various modifications and improvements without departing from the concept of this application, and these all fall within the protection scope of this application. Therefore, the protection scope of this patent application should be determined by the appended claims.

Claims

1. A context management method for an AI programming assistant based on a task state machine, characterized in that, Includes the following steps: Step 1: Construct the task state machine; Step 2: Selective organization based on the focus task path; Step 3: Verify the continuity of the task; Step 4: Next step planning and input parameter check based on the task state machine.

2. The context management method for an AI programming assistant based on a task state machine according to claim 1, characterized in that, The task state machine construction in step 1 is specifically as follows: Step 1-1, Task Identification and State Transition: The user's statement is segmented and tagged with part of speech using a general Chinese word segmentation and part-of-speech tagging tool. After matching the trigger word from the preset task trigger verb table, the continuous noun phrases / verb-object phrases that follow it are used as task entities for segmentation. The segmented task entities are normalized and written into the task description field of the task node to form the task node. The task node includes task ID, task description, task status, parent task information, dependent task ID, task output, key decisions involved in the task, list of steps to be executed, and focus sorting value; The task status includes to-do, doing, done, and pending. Step 1-2: Identify task dependency edges: If a user proposes task node B immediately after completing task node A, and task node B uses the output of task node A, then a dependency edge A→B is established. If the AI ​​programming assistant reads the file produced by task node A when executing task node B, then a dependency edge A→B is established. Steps 1-3: Determine the current focus task: The current focus task is the most recently activated task node among those whose task status is "doing". If there are multiple task nodes with a status of "completing," the one most recently explicitly mentioned by the user shall prevail. When there are multiple task nodes with a "completing" status and the user's current statement does not explicitly mention any task node, the following rules will be used to assist in the determination: Prioritize the task nodes involved in the most recent round of dialogue; if the most recent round involves multiple task nodes, select the task with the highest focus ranking value as the current focus task.

3. The context management method for an AI programming assistant based on a task state machine according to claim 2, characterized in that, The pending_steps list of task nodes in step 1-1 is generated based on the task description and the task outputs of task nodes with a completed status in their dependent task IDs when the task node is created or its task status is "doing". This list is stored in the pending_steps field. Specifically, it includes: Based on dependency output derivation: If the task output of a completed task that a task node depends on includes a preset file or table structure, then the pending_steps list should include the operation steps for that output. Task description extraction: Extract verb and noun components from the task description and generate corresponding operation steps according to the preset verb-object → operation step rewriting rules; When the output of a task that depends on another task changes or the user provides additional information about the scope of the task, the system regenerates the pending steps list (pending_steps) and overwrites the old value.

4. The context management method for an AI programming assistant based on a task state machine according to claim 2, characterized in that, The selective organization based on the focus task path in step 2 specifically includes: Step 2-1: Preserve the path of the focus task: Recursively query the parent task information of the current focus task up to the root task to form the focus task path, and retain the task description, task status, task output and key decisions of all task nodes on the path. Step 2-2, Dependency Path Preservation: Query the dependency edges of the current focus task and preserve the outputs and key decisions of the completed task nodes that are depended upon; Steps 2-3: Retain the original text of the three most recent rounds of dialogue; Steps 2-4: Non-path task compression: Compress task nodes with a completed status that are not on the path that the focus task depends on into a one-sentence summary; Steps 2-5: Pause pending task processing: Task nodes with a pending status and not on the dependency path are not retained in the context sent to the LLM model, but only in SQLite for later resumption.

5. The context management method for an AI programming assistant based on a task state machine according to claim 2, characterized in that, Step 3, task continuity inference and verification, specifically involves: Step 3-1: Construct the inference request: Using a fixed prompt template, including system instructions, a condensed context, and a specified JSON output format, the LLM model is required to infer the current task description, the next operation, and the completed outputs required to execute the next step based on the condensed context, and output the inference results in JSON format. Step 3-2: Obtain the inference results: Input the selectively processed context from step 2 into the LLM model to obtain JSON output; Step 3-3: Compare the inference results from Step 3-2 with the task state machine, including: A pre-trained sentence embedding model is used to encode the inference result current_task and the focus task description into vectors respectively. The cosine similarity between the two is calculated. When the cosine similarity is greater than the set threshold, it is considered to pass. Using the keyword set K_base of each step in the pending_steps list as a baseline, count the number of baseline keywords hit by the inference result next_step, and calculate the coverage rate according to the following formula. When the coverage rate is higher than the set threshold, it is considered as passing: Coverage = |next_step set of keywords hit ∩ K_base| / |K_base|; Check whether each output listed in the inference result required_outputs exists in the task output of the focus task and the task output of each task node that the focus task depends on. If all listed outputs exist, it is considered to pass. If all three items above pass, the task continuity inference verification is considered successful; if any one item fails, the task continuity inference verification is considered unsuccessful.

6. The context management method for an AI programming assistant based on a task state machine according to claim 5, characterized in that, When the task continuity inference verification fails, locate the missing information that caused the failure, and add the missing task nodes or outputs to the end of the context. Then return to step 2 to re-execute selective sorting and inference verification. Iterate a maximum of two times. If it still fails after two iterations, retain the original context.

7. The context management method for an AI programming assistant based on a task state machine according to claim 2, characterized in that, The next step planning and input parameter checking based on the task state machine in step 4 specifically includes: Step 4-1: Actively plan the next step based on the task state machine. The planning rules include: Dependency priority rule: Prioritize checking whether the task output of the task node with the status of "done" in the dependent task ID of the focus task has been used; Subtask unfolding rules: If the focus task has subtasks, that is, the parent task information of other task nodes points to the focus task, the subtasks are arranged in order of task status (to-do) taking precedence over task status (doing), and are used as candidate order for the next step of planning. Historical habit auxiliary rules: Query the task status transition log table task_transitions to count the most frequently executed next task type in history starting from the current task type, as a suggestion; where the task type is determined based on keyword extraction from the task description or preset task type classification rules; The statistical method involves counting records in the task transition log table task_transitions where the source task from_task is the current task type, grouping them by target task to_task, and taking the most frequent record as the suggestion; when historical records are insufficient, only the above dependency priority and subtask expansion rules are relied upon. Step 4-2: Before proceeding to the next task, check the compatibility of the outputs recorded in the task state machine of the input participants. The check items include output existence, decision consistency, and scope validity. The existence of outputs refers to checking whether the file / table / field referenced by the input parameters exists in the task output of the focus task or its dependent tasks. Decision consistency means checking whether the input parameters violate the recorded technical decisions; Range validity means checking whether the parameter value is within a reasonable range.

8. The context management method for an AI programming assistant based on a task state machine according to claim 7, characterized in that, The decision consistency is determined by the following rules to determine whether the input parameters violate the recorded technical decisions: Positive decision matching: For decisions such as adopting option X, check whether the input parameters contain keywords of alternative options that conflict with X. If they do, it is determined that the decision consistency is violated. Negative constraint detection: For decisions such as "prohibit / do not X", extract the prohibited target and check whether the input parameters affect the target. If so, it is determined that the decision consistency is violated.

9. The context management method for an AI programming assistant based on a task state machine according to claim 5, characterized in that, In step 3-2, when using the LLM model to obtain JSON output, if the JSON format is incorrect or contains output names that are not in any task output, the task continuity inference verification model is judged to be abnormal. At this point, skip the verification step, retain the current compression result, and record the exception log for later troubleshooting or replacement of the verification model; In step 1-2, when identifying task dependency edges, after establishing the dependency edge from task node A to B, it is checked whether task node B has read the file or field from the task output of task node A. If not read, it is marked as a weak dependency. In the subsequent selective sorting process based on the focus task path in step 2, the dependency node marked as a weak dependency will not be forcibly retained.

10. A context management system for an AI programming assistant based on a task state machine, characterized in that, Includes the following modules: State machine construction module: used for constructing task state machines; Selective Sorting Module: Used for selective sorting based on the focus task path; Inference and Verification Module: Used for inference and verification of task continuity; Next Step Planning and Checking Module: Used for next step planning and input parameter checking based on the task state machine.