Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

lisence: change the main lisence to AGPL-3.0 (#1085)

MaojiaShengce998873f94d
diff --git a/.pr_agent.toml b/.pr_agent.toml
index e9821c12e..2c7ba7310 100644
--- a/.pr_agent.toml
+++ b/.pr_agent.toml
@@ -2,7 +2,7 @@
# Qodo PR-Agent Configuration for OpenViking
# =============================================================================
# OpenViking: polyglot (Python/TypeScript/Rust) context database for AI agents.
-# By ByteDance/Volcengine — Apache-2.0 licensed.
+# By ByteDance/Volcengine — AGPL-3.0 licensed.
#
# Rules derived from: real bug history (PRs #505, #728, #749, #740/#745),
# codebase conventions, CI pipeline (ruff, mypy, pytest), and Qodo best
@@ -193,8 +193,8 @@ R6. LICENSE HEADERS
WHEN a new .py file is created in openviking/ or openviking_cli/
THEN it MUST contain at the top:
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
- # SPDX-License-Identifier: Apache-2.0
-BECAUSE Apache-2.0 compliance requires headers on all source files.
+ # SPDX-License-Identifier: AGPL-3.0
+BECAUSE AGPL-3.0 compliance requires headers on all source files.
Every existing file in these directories follows this convention.
R7. ERROR HANDLING
diff --git a/LICENSE b/LICENSE
index f49a4e16e..27268c8e4 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,201 +1,662 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
\ No newline at end of file
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do not
+control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes the unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of
+the rights granted or affirmed under this License. For example, you
+may not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the parties
+who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work for use in or with those products, unless
+you entered into that arrangement, or that patent license was granted,
+prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero
+General Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you to
+choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAM),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information about this, and how to apply and follow the GNU AGPL, see
+<https://www.gnu.org/licenses/>.
\ No newline at end of file
diff --git a/README.md b/README.md
index 1d6de1ab0..e7bcbec89 100644
--- a/README.md
+++ b/README.md
@@ -654,14 +654,19 @@ Let's work together to define and build the future of AI Agent context managemen
## License
-This project is licensed under the Apache License 2.0 - see the [LICENSE](./LICENSE) file for details.
+The OpenViking project uses different licenses for different components:
+
+- **Main Project**: AGPLv3 - see the [LICENSE](./LICENSE) file for details
+- **crates/ov_cli**: Apache 2.0 - see the [LICENSE](./crates/ov_cli/LICENSE) for details
+- **examples**: Apache 2.0 - see the [LICENSE](./examples/LICENSE) for details
+- **third_party**: Respective original licenses of third-party projects
<!-- Link Definitions -->
[release-shield]: https://img.shields.io/github/v/release/volcengine/OpenViking?color=369eff&labelColor=black&logo=github&style=flat-square
[release-link]: https://github.com/volcengine/OpenViking/releases
-[license-shield]: https://img.shields.io/badge/license-apache%202.0-white?labelColor=black&style=flat-square
+[license-shield]: https://img.shields.io/badge/license-AGPLv3-white?labelColor=black&style=flat-square
[license-shield-link]: https://github.com/volcengine/OpenViking/blob/main/LICENSE
[last-commit-shield]: https://img.shields.io/github/last-commit/volcengine/OpenViking?color=c4f042&labelColor=black&style=flat-square
[last-commit-shield-link]: https://github.com/volcengine/OpenViking/commits/main
diff --git a/README_CN.md b/README_CN.md
index a58691a85..c64168e64 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -687,14 +687,19 @@ OpenViking 仍处于早期阶段,有许多改进和探索的空间。我们真
## 许可证
-本项目采用 Apache License 2.0 许可证 - 详情请参见 [LICENSE](./LICENSE) 文件。
+OpenViking 项目不同组件采用不同的开源协议:
+
+- **主项目**: AGPLv3 - 详情请参见 [LICENSE](./LICENSE) 文件
+- **crates/ov_cli**: Apache 2.0 - 详情请参见 [LICENSE](./crates/ov_cli/LICENSE) 文件
+- **examples**: Apache 2.0 - 详情请参见 [LICENSE](./examples/LICENSE) 文件
+- **third_party**: 保留各三方项目的原有协议
<!-- Link Definitions -->
[release-shield]: https://img.shields.io/github/v/release/volcengine/OpenViking?color=369eff&labelColor=black&logo=github&style=flat-square
[release-link]: https://github.com/volcengine/OpenViking/releases
-[license-shield]: https://img.shields.io/badge/license-apache%202.0-white?labelColor=black&style=flat-square
+[license-shield]: https://img.shields.io/badge/license-AGPLv3-white?labelColor=black&style=flat-square
[license-shield-link]: https://github.com/volcengine/OpenViking/blob/main/LICENSE
[last-commit-shield]: https://img.shields.io/github/last-commit/volcengine/OpenViking?color=c4f042&labelColor=black&style=flat-square
[last-commit-shield-link]: https://github.com/volcengine/OpenViking/commcommits/main
diff --git a/README_JA.md b/README_JA.md
index bba6be1e7..d867e1531 100644
--- a/README_JA.md
+++ b/README_JA.md
@@ -617,14 +617,19 @@ AIエージェントのコンテキスト管理の未来を共に定義し、構
## ライセンス
-このプロジェクトはApache License 2.0の下でライセンスされています。詳細は[LICENSE](./LICENSE)ファイルを参照してください。
+OpenVikingプロジェクトは、コンポーネントごとに異なるライセンスを使用しています:
+
+- **メインプロジェクト**: AGPLv3 - 詳細は[LICENSE](./LICENSE)ファイルを参照してください
+- **crates/ov_cli**: Apache 2.0 - 詳細は[LICENSE](./crates/ov_cli/LICENSE)ファイルを参照してください
+- **examples**: Apache 2.0 - 詳細は[LICENSE](./examples/LICENSE)ファイルを参照してください
+- **third_party**: 各サードパーティプロジェクトの元のライセンス
<!-- リンク定義 -->
[release-shield]: https://img.shields.io/github/v/release/volcengine/OpenViking?color=369eff&labelColor=black&logo=github&style=flat-square
[release-link]: https://github.com/volcengine/OpenViking/releases
-[license-shield]: https://img.shields.io/badge/license-apache%202.0-white?labelColor=black&style=flat-square
+[license-shield]: https://img.shields.io/badge/license-AGPLv3-white?labelColor=black&style=flat-square
[license-shield-link]: https://github.com/volcengine/OpenViking/blob/main/LICENSE
[last-commit-shield]: https://img.shields.io/github/last-commit/volcengine/OpenViking?color=c4f042&labelColor=black&style=flat-square
[last-commit-shield-link]: https://github.com/volcengine/OpenViking/commits/main
diff --git a/bot/package-lock.json b/bot/package-lock.json
index d44d4c4a7..f0e456324 100644
--- a/bot/package-lock.json
+++ b/bot/package-lock.json
@@ -16,7 +16,7 @@
"version": "0.0.37",
"resolved": "https://registry.npmjs.org/@anthropic-ai/sandbox-runtime/-/sandbox-runtime-0.0.37.tgz",
"integrity": "sha512-KKzHoe4blXQpTEtbFLKP76PHsUerqlG5UNN+MQvXf0SVZDtawP9hHc9HiMgzvUXST2OMYl2Sk27k18d6684eoQ==",
- "license": "Apache-2.0",
+ "license": "AGPL-3.0",
"dependencies": {
"@pondwader/socks5-server": "^1.0.10",
"@types/lodash-es": "^4.17.12",
diff --git a/bot/tests/conftest.py b/bot/tests/conftest.py
index 9ace5753d..03b2d7435 100644
--- a/bot/tests/conftest.py
+++ b/bot/tests/conftest.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Global test fixtures"""
diff --git a/bot/tests/test_chat_functionality.py b/bot/tests/test_chat_functionality.py
index 27b353555..556a0e4bd 100644
--- a/bot/tests/test_chat_functionality.py
+++ b/bot/tests/test_chat_functionality.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for vikingbot chat functionality - single message and interactive modes."""
import tempfile
diff --git a/bot/vikingbot/channels/chat.py b/bot/vikingbot/channels/chat.py
index fe7dc65c4..d0fd6345e 100644
--- a/bot/vikingbot/channels/chat.py
+++ b/bot/vikingbot/channels/chat.py
@@ -1,21 +1,19 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Chat channel for interactive mode."""
import asyncio
import os
import signal
-import sys
from pathlib import Path
from typing import Any
-from loguru import logger
from rich.style import Style
-from vikingbot.bus.events import InboundMessage, OutboundMessage, OutboundEventType
+from vikingbot.bus.events import InboundMessage, OutboundEventType, OutboundMessage
from vikingbot.bus.queue import MessageBus
from vikingbot.channels.base import BaseChannel
-from vikingbot.config.schema import SessionKey, BaseChannelConfig
+from vikingbot.config.schema import BaseChannelConfig, SessionKey
class ChatChannelConfig(BaseChannelConfig):
@@ -71,10 +69,11 @@ class ChatChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None:
"""Send a message - display thinking events and store final response."""
- from vikingbot.cli.commands import console
from rich.markdown import Markdown
from rich.text import Text
+ from vikingbot.cli.commands import console
+
if msg.is_normal_message:
self._last_response = msg.content
self._response_received.set()
@@ -117,10 +116,9 @@ class ChatChannel(BaseChannel):
_flush_pending_tty_input,
_init_prompt_session,
_is_exit_command,
+ _read_interactive_input_async,
_restore_terminal,
- __logo__,
console,
- _read_interactive_input_async,
)
_init_prompt_session()
diff --git a/bot/vikingbot/channels/single_turn.py b/bot/vikingbot/channels/single_turn.py
index f618b816c..6e2a040cb 100644
--- a/bot/vikingbot/channels/single_turn.py
+++ b/bot/vikingbot/channels/single_turn.py
@@ -1,18 +1,18 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Single-turn channel - no extra output, just the result."""
import asyncio
+import json
from pathlib import Path
from typing import Any
-import json
from loguru import logger
-from vikingbot.bus.events import InboundMessage, OutboundMessage, OutboundEventType
+from vikingbot.bus.events import InboundMessage, OutboundMessage
from vikingbot.bus.queue import MessageBus
from vikingbot.channels.base import BaseChannel
-from vikingbot.config.schema import SessionKey, BaseChannelConfig
+from vikingbot.config.schema import BaseChannelConfig, SessionKey
class SingleTurnChannelConfig(BaseChannelConfig):
@@ -77,10 +77,11 @@ class SingleTurnChannel(BaseChannel):
try:
await asyncio.wait_for(self._response_received.wait(), timeout=3000.0)
if self._last_response:
- from vikingbot.cli.commands import console
from rich.markdown import Markdown
from rich.text import Text
+ from vikingbot.cli.commands import console
+
content = self._last_response or ""
body = Markdown(content) if self.markdown else Text(content)
console.print(body)
diff --git a/crates/ov_cli/LICENSE b/crates/ov_cli/LICENSE
new file mode 100644
index 000000000..8364a3e94
--- /dev/null
+++ b/crates/ov_cli/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited
+ to communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor
+ be liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if you agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
\ No newline at end of file
diff --git a/docs/en/faq/faq.md b/docs/en/faq/faq.md
index 24a42dfe8..5fb567293 100644
--- a/docs/en/faq/faq.md
+++ b/docs/en/faq/faq.md
@@ -386,7 +386,7 @@ client = ov.AsyncHTTPClient(url="http://localhost:1933", api_key="your-key")
### Is OpenViking open source?
-Yes, OpenViking is fully open source under the Apache 2.0 license.
+Yes, OpenViking main project is open source under the AGPL-3.0 license, and examples/ and crates/ov_cli are licensed under the Apache 2.0 license.
## Related Documentation
diff --git a/examples/LICENSE b/examples/LICENSE
new file mode 100644
index 000000000..b65287786
--- /dev/null
+++ b/examples/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited
+ to communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including but negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor
+ be liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Der Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if you agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
\ No newline at end of file
diff --git a/openviking/__init__.py b/openviking/__init__.py
index d0ada80d5..e7691c5ff 100644
--- a/openviking/__init__.py
+++ b/openviking/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
OpenViking - An Agent-native context database
diff --git a/openviking/agfs_manager.py b/openviking/agfs_manager.py
index 0b4375cbf..1f10282d2 100644
--- a/openviking/agfs_manager.py
+++ b/openviking/agfs_manager.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""AGFS Process Manager - Responsible for starting and stopping the AGFS server."""
import atexit
diff --git a/openviking/async_client.py b/openviking/async_client.py
index 1e92843c1..c57e9b8e5 100644
--- a/openviking/async_client.py
+++ b/openviking/async_client.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Async OpenViking client implementation (embedded mode only).
diff --git a/openviking/client.py b/openviking/client.py
index 444607c2a..21d9839d4 100644
--- a/openviking/client.py
+++ b/openviking/client.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
OpenViking client.
This module provides both synchronous and asynchronous clients.
diff --git a/openviking/client/__init__.py b/openviking/client/__init__.py
index ad76639f1..f12af9d3c 100644
--- a/openviking/client/__init__.py
+++ b/openviking/client/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""OpenViking Client module.
Provides client implementations for embedded (LocalClient) and HTTP (AsyncHTTPClient/SyncHTTPClient) modes.
diff --git a/openviking/client/local.py b/openviking/client/local.py
index 56080dfe2..4a45a0383 100644
--- a/openviking/client/local.py
+++ b/openviking/client/local.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Local Client for OpenViking.
Implements BaseClient interface using direct service calls (embedded mode).
@@ -398,6 +398,7 @@ class LocalClient(BaseClient):
If both content and parts are provided, parts takes precedence.
"""
from datetime import datetime
+
from openviking.message.part import Part, TextPart, part_from_dict
session = self._service.sessions.session(self._ctx, session_id)
diff --git a/openviking/client/session.py b/openviking/client/session.py
index e0c3ceced..d569ab63a 100644
--- a/openviking/client/session.py
+++ b/openviking/client/session.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Lightweight Session class for OpenViking client.
Session delegates all operations to the underlying Client (LocalClient or AsyncHTTPClient).
diff --git a/openviking/console/__init__.py b/openviking/console/__init__.py
index 878dcff6e..3d71e1049 100644
--- a/openviking/console/__init__.py
+++ b/openviking/console/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""OpenViking Console (standalone web dashboard).
diff --git a/openviking/console/app.py b/openviking/console/app.py
index 891d24851..3f8190fa7 100644
--- a/openviking/console/app.py
+++ b/openviking/console/app.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""FastAPI app for the standalone OpenViking console service."""
from __future__ import annotations
diff --git a/openviking/console/bootstrap.py b/openviking/console/bootstrap.py
index aca731129..1ad56a188 100644
--- a/openviking/console/bootstrap.py
+++ b/openviking/console/bootstrap.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Bootstrap entrypoint for OpenViking console service."""
from __future__ import annotations
diff --git a/openviking/console/config.py b/openviking/console/config.py
index ede3aec52..0b26c82eb 100644
--- a/openviking/console/config.py
+++ b/openviking/console/config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Configuration for the standalone OpenViking console service."""
from __future__ import annotations
diff --git a/openviking/core/__init__.py b/openviking/core/__init__.py
index 19e15538c..1c33e6c0a 100644
--- a/openviking/core/__init__.py
+++ b/openviking/core/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Core context abstractions for OpenViking."""
from openviking.core.building_tree import BuildingTree
diff --git a/openviking/core/building_tree.py b/openviking/core/building_tree.py
index 43207e293..5517a269f 100644
--- a/openviking/core/building_tree.py
+++ b/openviking/core/building_tree.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""BuildingTree container for OpenViking context trees."""
from typing import TYPE_CHECKING, Any, Dict, List, Optional
diff --git a/openviking/core/context.py b/openviking/core/context.py
index 763085703..be1ea5fa8 100644
--- a/openviking/core/context.py
+++ b/openviking/core/context.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Unified context class for OpenViking."""
from datetime import datetime, timezone
diff --git a/openviking/core/directories.py b/openviking/core/directories.py
index 4ca55baa4..c3216bd98 100644
--- a/openviking/core/directories.py
+++ b/openviking/core/directories.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Preset directory structure definitions for OpenViking.
diff --git a/openviking/core/mcp_converter.py b/openviking/core/mcp_converter.py
index 2faabaa9b..a080133c1 100644
--- a/openviking/core/mcp_converter.py
+++ b/openviking/core/mcp_converter.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""MCP to Skill converter."""
from typing import Any, Dict
diff --git a/openviking/core/skill_loader.py b/openviking/core/skill_loader.py
index 7e38dbaed..4e85c8d07 100644
--- a/openviking/core/skill_loader.py
+++ b/openviking/core/skill_loader.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""SKILL.md loader and parser."""
import re
diff --git a/openviking/crypto/__init__.py b/openviking/crypto/__init__.py
index 8de3defc4..e65228774 100644
--- a/openviking/crypto/__init__.py
+++ b/openviking/crypto/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
OpenViking Encryption Module
diff --git a/openviking/crypto/config.py b/openviking/crypto/config.py
index 109e8190f..9bcfbf8cf 100644
--- a/openviking/crypto/config.py
+++ b/openviking/crypto/config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Encryption module configuration management.
diff --git a/openviking/crypto/encryptor.py b/openviking/crypto/encryptor.py
index 953c2d1d6..ca6609ebb 100644
--- a/openviking/crypto/encryptor.py
+++ b/openviking/crypto/encryptor.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
File encryptor - envelope encryption implementation.
diff --git a/openviking/crypto/exceptions.py b/openviking/crypto/exceptions.py
index e0e54afe0..11af75f17 100644
--- a/openviking/crypto/exceptions.py
+++ b/openviking/crypto/exceptions.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Encryption module exception definitions.
"""
diff --git a/openviking/crypto/providers.py b/openviking/crypto/providers.py
index 3f8bf68a8..7c0e8daed 100644
--- a/openviking/crypto/providers.py
+++ b/openviking/crypto/providers.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Key provider abstractions and implementations.
diff --git a/openviking/eval/__init__.py b/openviking/eval/__init__.py
index a1a4ca492..f6a61f8d0 100644
--- a/openviking/eval/__init__.py
+++ b/openviking/eval/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Evaluation module for OpenViking.
"""
diff --git a/openviking/eval/ragas/__init__.py b/openviking/eval/ragas/__init__.py
index df2952105..38e88cc8f 100644
--- a/openviking/eval/ragas/__init__.py
+++ b/openviking/eval/ragas/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
RAGAS evaluator integration for OpenViking.
"""
diff --git a/openviking/eval/ragas/analyze_records.py b/openviking/eval/ragas/analyze_records.py
index 988c20de8..ad9ca808c 100644
--- a/openviking/eval/ragas/analyze_records.py
+++ b/openviking/eval/ragas/analyze_records.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Record Analysis CLI tool.
diff --git a/openviking/eval/ragas/base.py b/openviking/eval/ragas/base.py
index 17f0fca21..3b7dda17f 100644
--- a/openviking/eval/ragas/base.py
+++ b/openviking/eval/ragas/base.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Base evaluator class for OpenViking.
"""
diff --git a/openviking/eval/ragas/generator.py b/openviking/eval/ragas/generator.py
index 7acfcc91c..c064314ad 100644
--- a/openviking/eval/ragas/generator.py
+++ b/openviking/eval/ragas/generator.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Dataset generator for OpenViking evaluation.
"""
diff --git a/openviking/eval/ragas/pipeline.py b/openviking/eval/ragas/pipeline.py
index 0b877778d..360b9eabd 100644
--- a/openviking/eval/ragas/pipeline.py
+++ b/openviking/eval/ragas/pipeline.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
RAG Query Pipeline for OpenViking evaluation.
"""
diff --git a/openviking/eval/ragas/play_recorder.py b/openviking/eval/ragas/play_recorder.py
index 25f811253..c34b042c3 100644
--- a/openviking/eval/ragas/play_recorder.py
+++ b/openviking/eval/ragas/play_recorder.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Play recorder CLI tool.
diff --git a/openviking/eval/ragas/playback.py b/openviking/eval/ragas/playback.py
index 3a9b75e74..48baa1c83 100644
--- a/openviking/eval/ragas/playback.py
+++ b/openviking/eval/ragas/playback.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Playback module for IORecorder.
diff --git a/openviking/eval/ragas/rag_eval.py b/openviking/eval/ragas/rag_eval.py
index cab498944..997773022 100644
--- a/openviking/eval/ragas/rag_eval.py
+++ b/openviking/eval/ragas/rag_eval.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
RAG Evaluation CLI Tool for OpenViking.
diff --git a/openviking/eval/ragas/record_analysis.py b/openviking/eval/ragas/record_analysis.py
index 63b5ba973..8a1e55825 100644
--- a/openviking/eval/ragas/record_analysis.py
+++ b/openviking/eval/ragas/record_analysis.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Record Analysis module for IORecorder.
diff --git a/openviking/eval/ragas/types.py b/openviking/eval/ragas/types.py
index 3c8c7fa59..9f824dabc 100644
--- a/openviking/eval/ragas/types.py
+++ b/openviking/eval/ragas/types.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Data types for OpenViking evaluation module.
"""
diff --git a/openviking/eval/recorder/__init__.py b/openviking/eval/recorder/__init__.py
index 611b7c55d..7c8566e91 100644
--- a/openviking/eval/recorder/__init__.py
+++ b/openviking/eval/recorder/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
IO Recorder for OpenViking evaluation.
diff --git a/openviking/eval/recorder/async_writer.py b/openviking/eval/recorder/async_writer.py
index c5dabee62..4edfde5e4 100644
--- a/openviking/eval/recorder/async_writer.py
+++ b/openviking/eval/recorder/async_writer.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Async writer for IORecorder.
diff --git a/openviking/eval/recorder/playback.py b/openviking/eval/recorder/playback.py
index 9a6155c8e..00a849bb9 100644
--- a/openviking/eval/recorder/playback.py
+++ b/openviking/eval/recorder/playback.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Deprecated: Playback module for IORecorder.
diff --git a/openviking/eval/recorder/recorder.py b/openviking/eval/recorder/recorder.py
index c5869f1d8..03f60a9cf 100644
--- a/openviking/eval/recorder/recorder.py
+++ b/openviking/eval/recorder/recorder.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
IO Recorder implementation for OpenViking evaluation.
"""
diff --git a/openviking/eval/recorder/recording_client.py b/openviking/eval/recorder/recording_client.py
index 7bd5abcdd..a63ce91fa 100644
--- a/openviking/eval/recorder/recording_client.py
+++ b/openviking/eval/recorder/recording_client.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Recording AGFS Client wrapper.
diff --git a/openviking/eval/recorder/types.py b/openviking/eval/recorder/types.py
index 393a99701..dcd12c5db 100644
--- a/openviking/eval/recorder/types.py
+++ b/openviking/eval/recorder/types.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
IO Recorder types for OpenViking evaluation.
"""
diff --git a/openviking/eval/recorder/wrapper.py b/openviking/eval/recorder/wrapper.py
index 685bfb3b8..db4eb84ae 100644
--- a/openviking/eval/recorder/wrapper.py
+++ b/openviking/eval/recorder/wrapper.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Recorder wrapper for VikingFS and VikingDB.
diff --git a/openviking/message/__init__.py b/openviking/message/__init__.py
index 9fc6e9de4..8dbe7a3c0 100644
--- a/openviking/message/__init__.py
+++ b/openviking/message/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Message module - based on opencode Part design.
Message = role + parts
diff --git a/openviking/message/message.py b/openviking/message/message.py
index fdf185e07..3280dd06d 100644
--- a/openviking/message/message.py
+++ b/openviking/message/message.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Message class definition - based on opencode Message design.
Message = role + parts, supports serialization to JSONL.
diff --git a/openviking/message/part.py b/openviking/message/part.py
index 2ba1771f5..862ccd8a2 100644
--- a/openviking/message/part.py
+++ b/openviking/message/part.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Part type definitions - based on opencode Part design.
Message consists of multiple Parts, each Part has different type and purpose.
diff --git a/openviking/models/__init__.py b/openviking/models/__init__.py
index 819b3465d..236633478 100644
--- a/openviking/models/__init__.py
+++ b/openviking/models/__init__.py
@@ -1,2 +1,2 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
diff --git a/openviking/models/embedder/__init__.py b/openviking/models/embedder/__init__.py
index bceae2a8f..9b5be66e5 100644
--- a/openviking/models/embedder/__init__.py
+++ b/openviking/models/embedder/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
OpenViking Embedder Module
diff --git a/openviking/models/embedder/base.py b/openviking/models/embedder/base.py
index a8c23a5f7..9a9e5df3e 100644
--- a/openviking/models/embedder/base.py
+++ b/openviking/models/embedder/base.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import random
import time
from abc import ABC, abstractmethod
diff --git a/openviking/models/embedder/cohere_embedders.py b/openviking/models/embedder/cohere_embedders.py
index 3c5815d26..d49269ffe 100644
--- a/openviking/models/embedder/cohere_embedders.py
+++ b/openviking/models/embedder/cohere_embedders.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Antigravity / Dico Angelo
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Cohere dense embedder implementation.
Uses Cohere's Embed API v2 (https://docs.cohere.com/reference/embed).
diff --git a/openviking/models/embedder/gemini_embedders.py b/openviking/models/embedder/gemini_embedders.py
index 878fa80f5..c11d73e47 100644
--- a/openviking/models/embedder/gemini_embedders.py
+++ b/openviking/models/embedder/gemini_embedders.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Gemini Embedding 2 provider using the official google-genai SDK."""
from typing import Any, Dict, List, Optional
diff --git a/openviking/models/embedder/jina_embedders.py b/openviking/models/embedder/jina_embedders.py
index 84713ba21..f94650fcc 100644
--- a/openviking/models/embedder/jina_embedders.py
+++ b/openviking/models/embedder/jina_embedders.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Jina AI Embedder Implementation"""
from typing import Any, Dict, List, Optional
diff --git a/openviking/models/embedder/litellm_embedders.py b/openviking/models/embedder/litellm_embedders.py
index 4f10f99c0..ea24c8141 100644
--- a/openviking/models/embedder/litellm_embedders.py
+++ b/openviking/models/embedder/litellm_embedders.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""LiteLLM Embedder Implementation
Uses litellm to provide a unified embedding interface across many providers
diff --git a/openviking/models/embedder/minimax_embedders.py b/openviking/models/embedder/minimax_embedders.py
index faec9b913..aba462968 100644
--- a/openviking/models/embedder/minimax_embedders.py
+++ b/openviking/models/embedder/minimax_embedders.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""MiniMax Embedder Implementation via HTTP API"""
from typing import Any, Dict, List, Optional
diff --git a/openviking/models/embedder/openai_embedders.py b/openviking/models/embedder/openai_embedders.py
index c57ec9ff3..0ebabbeee 100644
--- a/openviking/models/embedder/openai_embedders.py
+++ b/openviking/models/embedder/openai_embedders.py
@@ -1,18 +1,18 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""OpenAI Embedder Implementation"""
from typing import Any, Dict, List, Optional
import openai
-from openviking.models.vlm.registry import DEFAULT_AZURE_API_VERSION
from openviking.models.embedder.base import (
DenseEmbedderBase,
EmbedResult,
HybridEmbedderBase,
SparseEmbedderBase,
)
+from openviking.models.vlm.registry import DEFAULT_AZURE_API_VERSION
from openviking.telemetry import get_current_telemetry
diff --git a/openviking/models/embedder/vikingdb_embedders.py b/openviking/models/embedder/vikingdb_embedders.py
index d28aac492..0253af9dc 100644
--- a/openviking/models/embedder/vikingdb_embedders.py
+++ b/openviking/models/embedder/vikingdb_embedders.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""VikingDB Embedder Implementation via HTTP API"""
from typing import Any, Dict, List, Optional
diff --git a/openviking/models/embedder/volcengine_embedders.py b/openviking/models/embedder/volcengine_embedders.py
index c2384ec88..7a3ef6f4e 100644
--- a/openviking/models/embedder/volcengine_embedders.py
+++ b/openviking/models/embedder/volcengine_embedders.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Volcengine Embedder Implementation"""
from typing import Any, Dict, List, Optional
diff --git a/openviking/models/embedder/voyage_embedders.py b/openviking/models/embedder/voyage_embedders.py
index e866f0a18..ed8d49f04 100644
--- a/openviking/models/embedder/voyage_embedders.py
+++ b/openviking/models/embedder/voyage_embedders.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Voyage AI dense embedder implementation."""
from typing import Any, Dict, List, Optional
diff --git a/openviking/models/vlm/__init__.py b/openviking/models/vlm/__init__.py
index e58b51966..7808098bb 100644
--- a/openviking/models/vlm/__init__.py
+++ b/openviking/models/vlm/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""VLM (Vision-Language Model) module"""
from .backends.litellm_vlm import LiteLLMVLMProvider
diff --git a/openviking/models/vlm/backends/litellm_vlm.py b/openviking/models/vlm/backends/litellm_vlm.py
index 4ee8c8921..ca4a36aa7 100644
--- a/openviking/models/vlm/backends/litellm_vlm.py
+++ b/openviking/models/vlm/backends/litellm_vlm.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""LiteLLM VLM Provider implementation with multi-provider support."""
import json
diff --git a/openviking/models/vlm/backends/openai_vlm.py b/openviking/models/vlm/backends/openai_vlm.py
index 98dbb4c30..05c28c768 100644
--- a/openviking/models/vlm/backends/openai_vlm.py
+++ b/openviking/models/vlm/backends/openai_vlm.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""OpenAI VLM backend implementation"""
import asyncio
@@ -8,10 +8,10 @@ import json
import logging
import time
from pathlib import Path
-from urllib.parse import urlparse
from typing import Any, Dict, List, Optional, Union
+from urllib.parse import urlparse
-from ..base import VLMBase, VLMResponse, ToolCall
+from ..base import ToolCall, VLMBase, VLMResponse
from ..registry import DEFAULT_AZURE_API_VERSION
logger = logging.getLogger(__name__)
@@ -22,6 +22,7 @@ _DASHSCOPE_HOSTS = {
"dashscope-intl.aliyuncs.com",
}
+
def _build_openai_client_kwargs(
provider: str,
api_key: str,
@@ -62,8 +63,11 @@ class OpenAIVLM(VLMBase):
except ImportError:
raise ImportError("Please install openai: pip install openai")
kwargs = _build_openai_client_kwargs(
- self.provider, self.api_key, self.api_base,
- self.api_version, self.extra_headers,
+ self.provider,
+ self.api_key,
+ self.api_base,
+ self.api_version,
+ self.extra_headers,
)
if self.provider == "azure":
self._sync_client = openai.AzureOpenAI(**kwargs)
@@ -79,8 +83,11 @@ class OpenAIVLM(VLMBase):
except ImportError:
raise ImportError("Please install openai: pip install openai")
kwargs = _build_openai_client_kwargs(
- self.provider, self.api_key, self.api_base,
- self.api_version, self.extra_headers,
+ self.provider,
+ self.api_key,
+ self.api_base,
+ self.api_version,
+ self.extra_headers,
)
if self.provider == "azure":
self._async_client = openai.AsyncAzureOpenAI(**kwargs)
@@ -106,15 +113,15 @@ class OpenAIVLM(VLMBase):
return host.lower() in _DASHSCOPE_HOSTS
- def _apply_provider_specific_extra_body(
- self, kwargs: Dict[str, Any], thinking: bool
- ) -> None:
+ def _apply_provider_specific_extra_body(self, kwargs: Dict[str, Any], thinking: bool) -> None:
"""Attach provider-specific raw body parameters understood by compatible APIs."""
if self._supports_enable_thinking():
kwargs["extra_body"] = {"enable_thinking": bool(thinking)}
def _update_token_usage_from_response(
- self, response, duration_seconds: float = 0.0,
+ self,
+ response,
+ duration_seconds: float = 0.0,
):
if hasattr(response, "usage") and response.usage:
prompt_tokens = response.usage.prompt_tokens
@@ -139,11 +146,7 @@ class OpenAIVLM(VLMBase):
args = json.loads(args)
except json.JSONDecodeError:
args = {"raw": args}
- tool_calls.append(ToolCall(
- id=tc.id,
- name=tc.function.name,
- arguments=args
- ))
+ tool_calls.append(ToolCall(id=tc.id, name=tc.function.name, arguments=args))
return tool_calls
def _build_vlm_response(self, response, has_tools: bool) -> Union[str, VLMResponse]:
@@ -318,7 +321,6 @@ class OpenAIVLM(VLMBase):
else:
kwargs_messages = [{"role": "user", "content": prompt}]
-
kwargs = {
"model": self.model or "gpt-4o-mini",
"messages": kwargs_messages,
@@ -348,7 +350,8 @@ class OpenAIVLM(VLMBase):
content = await self._process_streaming_response_async(response)
else:
self._update_token_usage_from_response(
- response, duration_seconds=elapsed,
+ response,
+ duration_seconds=elapsed,
)
content = self._extract_content_from_response(response)
diff --git a/openviking/models/vlm/backends/volcengine_vlm.py b/openviking/models/vlm/backends/volcengine_vlm.py
index 83a1f83d6..06616def1 100644
--- a/openviking/models/vlm/backends/volcengine_vlm.py
+++ b/openviking/models/vlm/backends/volcengine_vlm.py
@@ -1,22 +1,20 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""VolcEngine VLM backend implementation"""
-import asyncio
import base64
import json
import logging
-import time
from collections import OrderedDict
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
-from .openai_vlm import OpenAIVLM
-from ..base import VLMResponse, ToolCall
-
# Import run_async for sync-to-async calls
from openviking_cli.utils import run_async
+from ..base import ToolCall, VLMResponse
+from .openai_vlm import OpenAIVLM
+
logger = logging.getLogger(__name__)
@@ -72,8 +70,9 @@ class VolcEngineVLM(OpenAIVLM):
key_messages.append(filtered)
return json.dumps(key_messages, ensure_ascii=False, sort_keys=True)
-
- def _parse_messages_with_breakpoints(self, messages: List[Dict[str, Any]]) -> Tuple[List[List[Dict[str, Any]]], List[Dict[str, Any]]]:
+ def _parse_messages_with_breakpoints(
+ self, messages: List[Dict[str, Any]]
+ ) -> Tuple[List[List[Dict[str, Any]]], List[Dict[str, Any]]]:
"""Parse messages into static segment and dynamic messages.
Only the content BEFORE the first cache_control becomes the static segment.
@@ -89,23 +88,20 @@ class VolcEngineVLM(OpenAIVLM):
if first_breakpoint_idx > 0:
# 有 cache_control,取其之前的内容作为 static segment
- static_segment = messages[:first_breakpoint_idx+1]
- dynamic_messages = messages[first_breakpoint_idx+1:]
+ static_segment = messages[: first_breakpoint_idx + 1]
+ dynamic_messages = messages[first_breakpoint_idx + 1 :]
static_segments = [static_segment]
- print(f'static_segment={len(static_segment)}')
- print(f'dynamic_messages={len(dynamic_messages)}')
+ print(f"static_segment={len(static_segment)}")
+ print(f"dynamic_messages={len(dynamic_messages)}")
else:
# 没有 cache_control 或在第一个位置,全部作为 dynamic
static_segments = []
dynamic_messages = messages
-
return static_segments, dynamic_messages
async def _get_or_create_from_segments(
- self,
- segments: List[List[Dict[str, Any]]],
- end_idx: int
+ self, segments: List[List[Dict[str, Any]]], end_idx: int
) -> Optional[str]:
"""递归获取或创建 cache,从长到短尝试。
@@ -119,7 +115,6 @@ class VolcEngineVLM(OpenAIVLM):
if end_idx <= 0:
return None
-
def segments_to_messages(segs):
# 拼接前 end_idx 个 segments
msgs = []
@@ -130,14 +125,18 @@ class VolcEngineVLM(OpenAIVLM):
prefix = segments_to_messages(segments[:end_idx])
if end_idx == 1:
- response_id = await self._get_or_create_from_messages(prefix)
+ response_id = await self._get_or_create_from_messages(prefix)
return response_id
previous_response_id = await self._get_or_create_from_segments(segments, end_idx - 1)
- return await self._get_or_create_from_messages(segments_to_messages(segments[end_idx - 1: end_idx]), previous_response_id=previous_response_id)
-
+ return await self._get_or_create_from_messages(
+ segments_to_messages(segments[end_idx - 1 : end_idx]),
+ previous_response_id=previous_response_id,
+ )
- async def _get_or_create_from_messages(self, messages: List[Dict[str, Any]], previous_response_id=None) -> Optional[str]:
+ async def _get_or_create_from_messages(
+ self, messages: List[Dict[str, Any]], previous_response_id=None
+ ) -> Optional[str]:
"""从头创建新 cache。"""
# Check cache first
@@ -163,7 +162,6 @@ class VolcEngineVLM(OpenAIVLM):
logger.warning(f"[VolcEngineVLM] Failed to create new cache: {e}")
return None
-
async def responseapi_prefixcache_completion(
self,
static_segments: List[List[Dict[str, Any]]],
@@ -183,7 +181,9 @@ class VolcEngineVLM(OpenAIVLM):
"""
# 使用多段缓存获取 response_id
if static_segments:
- response_id = await self._get_or_create_from_segments(static_segments, len(static_segments))
+ response_id = await self._get_or_create_from_segments(
+ static_segments, len(static_segments)
+ )
else:
response_id = None
client = self.get_async_client()
@@ -216,7 +216,6 @@ class VolcEngineVLM(OpenAIVLM):
response = await client.responses.create(**kwargs)
return response
-
def get_client(self):
"""Get sync client"""
if self._sync_client is None:
@@ -248,14 +247,16 @@ class VolcEngineVLM(OpenAIVLM):
return self._async_client
def _update_token_usage_from_response(
- self, response, duration_seconds: float = 0.0,
+ self,
+ response,
+ duration_seconds: float = 0.0,
) -> None:
"""Update token usage from VolcEngine Responses API response."""
if hasattr(response, "usage") and response.usage:
u = response.usage
# Responses API uses input_tokens/output_tokens instead of prompt_tokens/completion_tokens
- prompt_tokens = getattr(u, 'input_tokens', 0) or 0
- completion_tokens = getattr(u, 'output_tokens', 0) or 0
+ prompt_tokens = getattr(u, "input_tokens", 0) or 0
+ completion_tokens = getattr(u, "output_tokens", 0) or 0
self.update_token_usage(
model_name=self.model or "unknown",
provider=self.provider,
@@ -274,9 +275,9 @@ class VolcEngineVLM(OpenAIVLM):
- response.usage: token usage
"""
# Debug: print response structure
- #logger.debug(f"[VolcEngineVLM] Response type: {type(response)}")
+ # logger.debug(f"[VolcEngineVLM] Response type: {type(response)}")
# logger.info(f"[VolcEngineVLM] Full response: {response}")
- if hasattr(response, 'output'):
+ if hasattr(response, "output"):
# logger.debug(f"[VolcEngineVLM] Output items: {len(response.output)}")
for i, item in enumerate(response.output):
# logger.debug(f"[VolcEngineVLM] Item {i}: type={getattr(item, 'type', 'unknown')}")
@@ -289,11 +290,11 @@ class VolcEngineVLM(OpenAIVLM):
tool_calls = []
finish_reason = "stop"
- if hasattr(response, 'output') and response.output:
+ if hasattr(response, "output") and response.output:
for item in response.output:
- item_type = getattr(item, 'type', None)
+ item_type = getattr(item, "type", None)
# Check if it's a function_call item (Responses API format)
- if item_type == 'function_call':
+ if item_type == "function_call":
# logger.debug(f"[VolcEngineVLM] Found function_call tool call")
args = item.arguments
if isinstance(args, str):
@@ -301,28 +302,26 @@ class VolcEngineVLM(OpenAIVLM):
args = json.loads(args)
except json.JSONDecodeError:
args = {"raw": args}
- tool_calls.append(ToolCall(
- id=item.call_id or "",
- name=item.name or "",
- arguments=args
- ))
+ tool_calls.append(
+ ToolCall(id=item.call_id or "", name=item.name or "", arguments=args)
+ )
finish_reason = "tool_calls"
# Check if it's a message item (Chat API compatibility)
- elif item_type == 'message':
+ elif item_type == "message":
message = item
- if hasattr(message, 'content'):
+ if hasattr(message, "content"):
# Content can be a list or string
if isinstance(message.content, list):
for block in message.content:
- if hasattr(block, 'type') and block.type == 'output_text':
+ if hasattr(block, "type") and block.type == "output_text":
content = block.text or ""
- elif hasattr(block, 'text'):
+ elif hasattr(block, "text"):
content = block.text or ""
else:
content = message.content or ""
# Parse tool calls from message
- if hasattr(message, 'tool_calls') and message.tool_calls:
+ if hasattr(message, "tool_calls") and message.tool_calls:
# logger.debug(f"[VolcEngineVLM] Found {len(message.tool_calls)} tool calls in message")
for tc in message.tool_calls:
args = tc.arguments
@@ -337,29 +336,27 @@ class VolcEngineVLM(OpenAIVLM):
if not tool_name:
tool_name = tc.function.name
except AttributeError:
- tool_name = tc.function.name if hasattr(tc, 'function') else ""
- tool_calls.append(ToolCall(
- id=tc.id or "",
- name=tool_name or "",
- arguments=args
- ))
+ tool_name = tc.function.name if hasattr(tc, "function") else ""
+ tool_calls.append(
+ ToolCall(id=tc.id or "", name=tool_name or "", arguments=args)
+ )
- finish_reason = getattr(message, 'finish_reason', 'stop') or 'stop'
+ finish_reason = getattr(message, "finish_reason", "stop") or "stop"
# Extract usage
usage = {}
- if hasattr(response, 'usage') and response.usage:
+ if hasattr(response, "usage") and response.usage:
u = response.usage
usage = {
- "prompt_tokens": getattr(u, 'input_tokens', 0),
- "completion_tokens": getattr(u, 'output_tokens', 0),
- "total_tokens": getattr(u, 'total_tokens', 0),
+ "prompt_tokens": getattr(u, "input_tokens", 0),
+ "completion_tokens": getattr(u, "output_tokens", 0),
+ "total_tokens": getattr(u, "total_tokens", 0),
}
# Handle cached tokens
- input_details = getattr(u, 'input_tokens_details', None)
+ input_details = getattr(u, "input_tokens_details", None)
if input_details:
usage["prompt_tokens_details"] = {
- "cached_tokens": getattr(input_details, 'cached_tokens', 0),
+ "cached_tokens": getattr(input_details, "cached_tokens", 0),
}
if has_tools:
@@ -385,13 +382,15 @@ class VolcEngineVLM(OpenAIVLM):
Uses VolcEngine Responses API with prefix cache.
Delegates to async implementation.
"""
- return run_async(self.get_completion_async(
- prompt=prompt,
- thinking=thinking,
- tools=tools,
- tool_choice=tool_choice,
- messages=messages,
- ))
+ return run_async(
+ self.get_completion_async(
+ prompt=prompt,
+ thinking=thinking,
+ tools=tools,
+ tool_choice=tool_choice,
+ messages=messages,
+ )
+ )
def _convert_messages_to_input(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Convert OpenAI-style messages to VolcEngine Responses API input format.
@@ -413,6 +412,7 @@ class VolcEngineVLM(OpenAIVLM):
# Handle tool_call role with content as dict {name, args, result}
if role == "tool_call" and isinstance(content, dict):
import json
+
content_str = json.dumps(content, ensure_ascii=False)
role = "user" # Convert tool_call to user
else:
@@ -450,7 +450,12 @@ class VolcEngineVLM(OpenAIVLM):
data_urls = [u for u in image_urls if u.startswith("data:")]
if data_urls:
# Append image references to content
- content = content + "\n[Images: " + ", ".join([f"data URL ({i+1})" for i in range(len(data_urls))]) + "]"
+ content = (
+ content
+ + "\n[Images: "
+ + ", ".join([f"data URL ({i + 1})" for i in range(len(data_urls))])
+ + "]"
+ )
# Ensure content is a string, use placeholder if empty
content_str = str(content) if content else "[empty]"
@@ -467,10 +472,12 @@ class VolcEngineVLM(OpenAIVLM):
role = "user"
# Simple format: role + content (no type field)
- input_messages.append({
- "role": role,
- "content": content_str,
- })
+ input_messages.append(
+ {
+ "role": role,
+ "content": content_str,
+ }
+ )
return input_messages
@@ -491,31 +498,37 @@ class VolcEngineVLM(OpenAIVLM):
# Check if it's OpenAI format: {"type": "function", "function": {...}}
if tool.get("type") == "function" and "function" in tool:
func = tool["function"]
- converted.append({
- "type": "function", # Keep the type field
- "name": func.get("name", ""),
- "description": func.get("description", ""),
- "parameters": func.get("parameters", {}),
- })
+ converted.append(
+ {
+ "type": "function", # Keep the type field
+ "name": func.get("name", ""),
+ "description": func.get("description", ""),
+ "parameters": func.get("parameters", {}),
+ }
+ )
elif "function" in tool:
# Has function but no type
func = tool["function"]
- converted.append({
- "type": "function",
- "name": func.get("name", ""),
- "description": func.get("description", ""),
- "parameters": func.get("parameters", {}),
- })
+ converted.append(
+ {
+ "type": "function",
+ "name": func.get("name", ""),
+ "description": func.get("description", ""),
+ "parameters": func.get("parameters", {}),
+ }
+ )
else:
# Already in correct format or other format
# Ensure it has type: function
if tool.get("type") != "function":
- converted.append({
- "type": "function",
- "name": tool.get("name", ""),
- "description": tool.get("description", ""),
- "parameters": tool.get("parameters", {}),
- })
+ converted.append(
+ {
+ "type": "function",
+ "name": tool.get("name", ""),
+ "description": tool.get("description", ""),
+ "parameters": tool.get("parameters", {}),
+ }
+ )
else:
# Keep as is
converted.append(tool)
@@ -564,12 +577,14 @@ class VolcEngineVLM(OpenAIVLM):
except Exception as e:
last_error = e
# Log token info from error response if available
- error_response = getattr(e, 'response', None)
- if error_response and hasattr(error_response, 'usage'):
+ error_response = getattr(e, "response", None)
+ if error_response and hasattr(error_response, "usage"):
u = error_response.usage
- prompt_tokens = getattr(u, 'input_tokens', 0) or 0
- completion_tokens = getattr(u, 'output_tokens', 0) or 0
- logger.info(f"[VolcEngineVLM] Error response - Input tokens: {prompt_tokens}, Output tokens: {completion_tokens}")
+ prompt_tokens = getattr(u, "input_tokens", 0) or 0
+ completion_tokens = getattr(u, "output_tokens", 0) or 0
+ logger.info(
+ f"[VolcEngineVLM] Error response - Input tokens: {prompt_tokens}, Output tokens: {completion_tokens}"
+ )
logger.warning(f"[VolcEngineVLM] Request failed: {e}")
raise last_error
@@ -645,7 +660,7 @@ class VolcEngineVLM(OpenAIVLM):
b64 = base64.b64encode(image).decode("utf-8")
mime_type = self._detect_image_format(image)
# logger.info(
- # f"[VolcEngineVLM] Preparing image from bytes, size={len(image)}, detected mime={mime_type}"
+ # f"[VolcEngineVLM] Preparing image from bytes, size={len(image)}, detected mime={mime_type}"
# )
return {
"type": "image_url",
@@ -700,13 +715,15 @@ class VolcEngineVLM(OpenAIVLM):
Uses VolcEngine Responses API with prefix cache.
Delegates to async implementation.
"""
- return run_async(self.get_vision_completion_async(
- prompt=prompt,
- images=images,
- thinking=thinking,
- tools=tools,
- messages=messages,
- ))
+ return run_async(
+ self.get_vision_completion_async(
+ prompt=prompt,
+ images=images,
+ thinking=thinking,
+ tools=tools,
+ messages=messages,
+ )
+ )
async def get_vision_completion_async(
self,
diff --git a/openviking/models/vlm/base.py b/openviking/models/vlm/base.py
index 7ff039a09..c54285ad4 100644
--- a/openviking/models/vlm/base.py
+++ b/openviking/models/vlm/base.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""VLM base interface and abstract classes"""
import re
diff --git a/openviking/models/vlm/llm.py b/openviking/models/vlm/llm.py
index f2fc70dd4..e1cde6ccf 100644
--- a/openviking/models/vlm/llm.py
+++ b/openviking/models/vlm/llm.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
LLM utilities for OpenViking.
@@ -33,7 +33,7 @@ def parse_json_from_response(response: Union[str, Any]) -> Optional[Any]:
Optional[Any]: Parsed JSON object, None if parsing fails
"""
# Handle VLMResponse - extract content
- if hasattr(response, 'content'):
+ if hasattr(response, "content"):
response = response.content
if response is None:
@@ -199,7 +199,9 @@ class StructuredVLM:
if schema and not messages:
prompt = f"{prompt}\n\n{get_json_schema_prompt(schema)}"
- response = await self._get_vlm().get_completion_async(prompt, thinking, max_retries, tools, messages)
+ response = await self._get_vlm().get_completion_async(
+ prompt, thinking, max_retries, tools, messages
+ )
return parse_json_from_response(response)
def complete_model(
@@ -261,4 +263,6 @@ class StructuredVLM:
messages: Optional[List[Dict[str, Any]]] = None,
) -> Union[str, Any]:
"""Async vision completion."""
- return await self._get_vlm().get_vision_completion_async(prompt, images, thinking, tools, messages)
+ return await self._get_vlm().get_vision_completion_async(
+ prompt, images, thinking, tools, messages
+ )
diff --git a/openviking/models/vlm/registry.py b/openviking/models/vlm/registry.py
index c650dfe58..d69154764 100644
--- a/openviking/models/vlm/registry.py
+++ b/openviking/models/vlm/registry.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Provider Registry — single source of truth for LLM provider metadata.
diff --git a/openviking/models/vlm/token_usage.py b/openviking/models/vlm/token_usage.py
index 8b3219c14..f4cce7bd8 100644
--- a/openviking/models/vlm/token_usage.py
+++ b/openviking/models/vlm/token_usage.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""VLM Token usage monitoring data structures"""
from dataclasses import dataclass, field
diff --git a/openviking/parse/__init__.py b/openviking/parse/__init__.py
index 344fa25a5..b266a1dae 100644
--- a/openviking/parse/__init__.py
+++ b/openviking/parse/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Document parsers for various formats."""
from openviking.parse.base import NodeType, ParseResult, ResourceNode, create_parse_result
diff --git a/openviking/parse/base.py b/openviking/parse/base.py
index 91eec9009..2d63c66b4 100644
--- a/openviking/parse/base.py
+++ b/openviking/parse/base.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Base parser interface for OpenViking document processing.
diff --git a/openviking/parse/converter.py b/openviking/parse/converter.py
index 52d65c567..2f627ea44 100644
--- a/openviking/parse/converter.py
+++ b/openviking/parse/converter.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Document converters for consistent rendering."""
import asyncio
diff --git a/openviking/parse/custom.py b/openviking/parse/custom.py
index 78636a9fc..601d72099 100644
--- a/openviking/parse/custom.py
+++ b/openviking/parse/custom.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Custom parser protocol and wrappers for OpenViking.
diff --git a/openviking/parse/directory_scan.py b/openviking/parse/directory_scan.py
index 4b854071e..151b850aa 100644
--- a/openviking/parse/directory_scan.py
+++ b/openviking/parse/directory_scan.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Directory pre-scan validation module for OpenViking.
diff --git a/openviking/parse/ovpack/__init__.py b/openviking/parse/ovpack/__init__.py
index 819b3465d..236633478 100644
--- a/openviking/parse/ovpack/__init__.py
+++ b/openviking/parse/ovpack/__init__.py
@@ -1,2 +1,2 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
diff --git a/openviking/parse/parsers/__init__.py b/openviking/parse/parsers/__init__.py
index 75bf57e70..6ce39e4b3 100644
--- a/openviking/parse/parsers/__init__.py
+++ b/openviking/parse/parsers/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from .base_parser import BaseParser
from .code import CodeRepositoryParser
diff --git a/openviking/parse/parsers/base_parser.py b/openviking/parse/parsers/base_parser.py
index 4345d6232..be2ec403b 100644
--- a/openviking/parse/parsers/base_parser.py
+++ b/openviking/parse/parsers/base_parser.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from abc import ABC, abstractmethod
from pathlib import Path
from typing import List, Optional, Union
diff --git a/openviking/parse/parsers/code/__init__.py b/openviking/parse/parsers/code/__init__.py
index ba47c1a5b..d9b42a345 100644
--- a/openviking/parse/parsers/code/__init__.py
+++ b/openviking/parse/parsers/code/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from .code import CodeRepositoryParser
diff --git a/openviking/parse/parsers/code/ast/__init__.py b/openviking/parse/parsers/code/ast/__init__.py
index 45f8cf83d..3bd2ca40b 100644
--- a/openviking/parse/parsers/code/ast/__init__.py
+++ b/openviking/parse/parsers/code/ast/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Public API for AST-based code skeleton extraction."""
from typing import Optional
diff --git a/openviking/parse/parsers/code/ast/extractor.py b/openviking/parse/parsers/code/ast/extractor.py
index 46c60f45f..3e0f7826b 100644
--- a/openviking/parse/parsers/code/ast/extractor.py
+++ b/openviking/parse/parsers/code/ast/extractor.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""ASTExtractor: language detection + dispatch to per-language extractors."""
import importlib
diff --git a/openviking/parse/parsers/code/ast/languages/__init__.py b/openviking/parse/parsers/code/ast/languages/__init__.py
index 819b3465d..236633478 100644
--- a/openviking/parse/parsers/code/ast/languages/__init__.py
+++ b/openviking/parse/parsers/code/ast/languages/__init__.py
@@ -1,2 +1,2 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
diff --git a/openviking/parse/parsers/code/ast/languages/base.py b/openviking/parse/parsers/code/ast/languages/base.py
index 8d9d01e8b..e474d941d 100644
--- a/openviking/parse/parsers/code/ast/languages/base.py
+++ b/openviking/parse/parsers/code/ast/languages/base.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Abstract base class for language-specific AST extractors."""
from abc import ABC, abstractmethod
diff --git a/openviking/parse/parsers/code/ast/languages/cpp.py b/openviking/parse/parsers/code/ast/languages/cpp.py
index 56a5ac900..cb4a4bd2e 100644
--- a/openviking/parse/parsers/code/ast/languages/cpp.py
+++ b/openviking/parse/parsers/code/ast/languages/cpp.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""C/C++ AST extractor using tree-sitter-cpp."""
from typing import List, Optional
diff --git a/openviking/parse/parsers/code/ast/languages/csharp.py b/openviking/parse/parsers/code/ast/languages/csharp.py
index f47f0cbb8..7394e62e0 100644
--- a/openviking/parse/parsers/code/ast/languages/csharp.py
+++ b/openviking/parse/parsers/code/ast/languages/csharp.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""C# AST extractor using tree-sitter-c-sharp."""
import re
diff --git a/openviking/parse/parsers/code/ast/languages/go.py b/openviking/parse/parsers/code/ast/languages/go.py
index d3ca44f0c..7a61a2ea5 100644
--- a/openviking/parse/parsers/code/ast/languages/go.py
+++ b/openviking/parse/parsers/code/ast/languages/go.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Go AST extractor using tree-sitter-go."""
from typing import List
diff --git a/openviking/parse/parsers/code/ast/languages/java.py b/openviking/parse/parsers/code/ast/languages/java.py
index 79de06dc2..eec544be5 100644
--- a/openviking/parse/parsers/code/ast/languages/java.py
+++ b/openviking/parse/parsers/code/ast/languages/java.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Java AST extractor using tree-sitter-java."""
from typing import List
diff --git a/openviking/parse/parsers/code/ast/languages/js_ts.py b/openviking/parse/parsers/code/ast/languages/js_ts.py
index d04226820..424cc3c08 100644
--- a/openviking/parse/parsers/code/ast/languages/js_ts.py
+++ b/openviking/parse/parsers/code/ast/languages/js_ts.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""JavaScript/TypeScript AST extractor using tree-sitter."""
from typing import List
diff --git a/openviking/parse/parsers/code/ast/languages/python.py b/openviking/parse/parsers/code/ast/languages/python.py
index b16369728..af573a6b9 100644
--- a/openviking/parse/parsers/code/ast/languages/python.py
+++ b/openviking/parse/parsers/code/ast/languages/python.py
@@ -1,8 +1,8 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Python AST extractor using tree-sitter-python."""
-from typing import List, Optional
+from typing import List
from openviking.parse.parsers.code.ast.languages.base import LanguageExtractor
from openviking.parse.parsers.code.ast.skeleton import ClassSkeleton, CodeSkeleton, FunctionSig
diff --git a/openviking/parse/parsers/code/ast/languages/rust.py b/openviking/parse/parsers/code/ast/languages/rust.py
index 953d25b86..1dde6b99a 100644
--- a/openviking/parse/parsers/code/ast/languages/rust.py
+++ b/openviking/parse/parsers/code/ast/languages/rust.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Rust AST extractor using tree-sitter-rust."""
from typing import List
diff --git a/openviking/parse/parsers/code/ast/skeleton.py b/openviking/parse/parsers/code/ast/skeleton.py
index 110e882ab..739e99f1e 100644
--- a/openviking/parse/parsers/code/ast/skeleton.py
+++ b/openviking/parse/parsers/code/ast/skeleton.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""CodeSkeleton dataclasses and to_text() serialization."""
import re
diff --git a/openviking/parse/parsers/code/code.py b/openviking/parse/parsers/code/code.py
index d7270babc..91635e093 100644
--- a/openviking/parse/parsers/code/code.py
+++ b/openviking/parse/parsers/code/code.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Code Repository Parser.
diff --git a/openviking/parse/parsers/constants.py b/openviking/parse/parsers/constants.py
index cb0bf7012..51ae55b35 100644
--- a/openviking/parse/parsers/constants.py
+++ b/openviking/parse/parsers/constants.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Constants for CodeRepositoryParser.
diff --git a/openviking/parse/parsers/directory.py b/openviking/parse/parsers/directory.py
index da27b659d..0244b3d65 100644
--- a/openviking/parse/parsers/directory.py
+++ b/openviking/parse/parsers/directory.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Directory parser for OpenViking.
diff --git a/openviking/parse/parsers/epub.py b/openviking/parse/parsers/epub.py
index c5c7e063d..072a6380c 100644
--- a/openviking/parse/parsers/epub.py
+++ b/openviking/parse/parsers/epub.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
EPub (.epub) parser for OpenViking.
diff --git a/openviking/parse/parsers/excel.py b/openviking/parse/parsers/excel.py
index 2da44ce30..21e07151c 100644
--- a/openviking/parse/parsers/excel.py
+++ b/openviking/parse/parsers/excel.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Excel (.xlsx/.xls/.xlsm) parser for OpenViking.
@@ -142,7 +142,9 @@ class ExcelParser(BaseParser):
dt = xlrd.xldate_as_tuple(cell.value, wb.datemode)
# Include time component if non-zero
if dt[3] or dt[4] or dt[5]:
- return f"{dt[0]:04d}-{dt[1]:02d}-{dt[2]:02d} {dt[3]:02d}:{dt[4]:02d}:{dt[5]:02d}"
+ return (
+ f"{dt[0]:04d}-{dt[1]:02d}-{dt[2]:02d} {dt[3]:02d}:{dt[4]:02d}:{dt[5]:02d}"
+ )
return f"{dt[0]:04d}-{dt[1]:02d}-{dt[2]:02d}"
except Exception:
return str(cell.value)
@@ -151,8 +153,13 @@ class ExcelParser(BaseParser):
if cell.ctype == xlrd.XL_CELL_ERROR:
# xlrd error code map
error_map = {
- 0x00: "#NULL!", 0x07: "#DIV/0!", 0x0F: "#VALUE!",
- 0x17: "#REF!", 0x1D: "#NAME?", 0x24: "#NUM!", 0x2A: "#N/A",
+ 0x00: "#NULL!",
+ 0x07: "#DIV/0!",
+ 0x0F: "#VALUE!",
+ 0x17: "#REF!",
+ 0x1D: "#NAME?",
+ 0x24: "#NUM!",
+ 0x2A: "#N/A",
}
return error_map.get(cell.value, f"#ERR({cell.value})")
if cell.ctype == xlrd.XL_CELL_NUMBER:
diff --git a/openviking/parse/parsers/feishu.py b/openviking/parse/parsers/feishu.py
index 193d00ddb..3e462997b 100644
--- a/openviking/parse/parsers/feishu.py
+++ b/openviking/parse/parsers/feishu.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Feishu/Lark cloud document parser for OpenViking.
@@ -73,32 +73,93 @@ class FeishuParser(BaseParser):
# Primary dispatch mechanism for reliable block detection.
# Source: Feishu OpenAPI documentation + lark-oapi SDK Block class.
_BLOCK_TYPE_TO_ATTR = {
- 1: "page", 2: "text",
- 3: "heading1", 4: "heading2", 5: "heading3", 6: "heading4",
- 7: "heading5", 8: "heading6", 9: "heading7", 10: "heading8", 11: "heading9",
- 12: "bullet", 13: "ordered", 14: "code", 15: "quote",
- 17: "todo", 18: "bitable", 19: "callout",
- 22: "divider", 24: "file",
+ 1: "page",
+ 2: "text",
+ 3: "heading1",
+ 4: "heading2",
+ 5: "heading3",
+ 6: "heading4",
+ 7: "heading5",
+ 8: "heading6",
+ 9: "heading7",
+ 10: "heading8",
+ 11: "heading9",
+ 12: "bullet",
+ 13: "ordered",
+ 14: "code",
+ 15: "quote",
+ 17: "todo",
+ 18: "bitable",
+ 19: "callout",
+ 22: "divider",
+ 24: "file",
27: "image",
30: "sheet",
- 31: "table", 32: "table_cell",
+ 31: "table",
+ 32: "table_cell",
34: "quote_container",
}
# All known content attribute names on SDK Block objects (for fallback detection).
- _KNOWN_CONTENT_ATTRS = frozenset({
- "page", "text", "heading1", "heading2", "heading3", "heading4",
- "heading5", "heading6", "heading7", "heading8", "heading9",
- "bullet", "ordered", "code", "quote", "todo", "callout",
- "divider", "image", "table", "table_cell", "quote_container",
- "sheet", "file", "bitable", "equation", "task",
- "grid", "grid_column", "iframe", "board", "chat_card", "diagram",
- "agenda", "agenda_item", "agenda_item_content", "agenda_item_title",
- "ai_template", "isv", "jira_issue", "link_preview", "meeting_notes_qa",
- "mindnote", "okr", "okr_key_result", "okr_objective", "okr_progress",
- "project", "reference_base", "reference_synced", "source_synced",
- "sub_page_list", "undefined", "view", "wiki_catalog",
- })
+ _KNOWN_CONTENT_ATTRS = frozenset(
+ {
+ "page",
+ "text",
+ "heading1",
+ "heading2",
+ "heading3",
+ "heading4",
+ "heading5",
+ "heading6",
+ "heading7",
+ "heading8",
+ "heading9",
+ "bullet",
+ "ordered",
+ "code",
+ "quote",
+ "todo",
+ "callout",
+ "divider",
+ "image",
+ "table",
+ "table_cell",
+ "quote_container",
+ "sheet",
+ "file",
+ "bitable",
+ "equation",
+ "task",
+ "grid",
+ "grid_column",
+ "iframe",
+ "board",
+ "chat_card",
+ "diagram",
+ "agenda",
+ "agenda_item",
+ "agenda_item_content",
+ "agenda_item_title",
+ "ai_template",
+ "isv",
+ "jira_issue",
+ "link_preview",
+ "meeting_notes_qa",
+ "mindnote",
+ "okr",
+ "okr_key_result",
+ "okr_objective",
+ "okr_progress",
+ "project",
+ "reference_base",
+ "reference_synced",
+ "source_synced",
+ "sub_page_list",
+ "undefined",
+ "view",
+ "wiki_catalog",
+ }
+ )
# Document type → parse method name mapping.
# Wiki nodes are resolved to one of these types via _resolve_wiki_node.
@@ -150,11 +211,7 @@ class FeishuParser(BaseParser):
)
domain = config.domain or "https://open.feishu.cn"
self._client = (
- lark.Client.builder()
- .app_id(app_id)
- .app_secret(app_secret)
- .domain(domain)
- .build()
+ lark.Client.builder().app_id(app_id).app_secret(app_secret).domain(domain).build()
)
return self._client
@@ -178,9 +235,7 @@ class FeishuParser(BaseParser):
# ========== Main Parse ==========
- async def parse(
- self, source: Union[str, Path], instruction: str = "", **kwargs
- ) -> ParseResult:
+ async def parse(self, source: Union[str, Path], instruction: str = "", **kwargs) -> ParseResult:
"""Parse a Feishu cloud document URL."""
url = str(source)
start_time = time.time()
@@ -201,9 +256,7 @@ class FeishuParser(BaseParser):
f"Unsupported Feishu document type: {doc_type}. "
f"Supported: {list(self._DOC_TYPE_HANDLERS.keys())}"
)
- markdown, doc_title = await asyncio.to_thread(
- getattr(self, handler_name), token
- )
+ markdown, doc_title = await asyncio.to_thread(getattr(self, handler_name), token)
if title:
doc_title = title
@@ -261,8 +314,7 @@ class FeishuParser(BaseParser):
response = client.wiki.v2.space.get_node(request)
if not response.success():
raise RuntimeError(
- f"Failed to resolve wiki node {token}: "
- f"code={response.code}, msg={response.msg}"
+ f"Failed to resolve wiki node {token}: code={response.code}, msg={response.msg}"
)
node = response.data.node
obj_type = node.obj_type or ""
@@ -306,7 +358,9 @@ class FeishuParser(BaseParser):
if block.page is not None:
continue # Skip page container
- line = self._block_to_markdown(block, block_map, ordered_counter, document_id=document_id)
+ line = self._block_to_markdown(
+ block, block_map, ordered_counter, document_id=document_id
+ )
if line is not None:
markdown_lines.append(line)
@@ -374,8 +428,9 @@ class FeishuParser(BaseParser):
return attr
return None
- def _block_to_markdown(self, block, block_map: Dict, ordered_counter: Dict[str, int],
- document_id: str = "") -> Optional[str]:
+ def _block_to_markdown(
+ self, block, block_map: Dict, ordered_counter: Dict[str, int], document_id: str = ""
+ ) -> Optional[str]:
"""Convert a single SDK block object to markdown string.
Uses block_type integer for primary dispatch, with attribute whitelist
@@ -578,8 +633,9 @@ class FeishuParser(BaseParser):
# ========== Embedded Sheet in Docx ==========
- def _embedded_sheet_to_markdown(self, block, block_map: Dict = None, *,
- document_id: str = "", **_) -> Optional[str]:
+ def _embedded_sheet_to_markdown(
+ self, block, block_map: Dict = None, *, document_id: str = "", **_
+ ) -> Optional[str]:
"""Convert an embedded sheet block to markdown table.
These blocks appear in docx documents when a user embeds a spreadsheet
@@ -604,9 +660,7 @@ class FeishuParser(BaseParser):
return None
data = json.loads(raw_resp.raw.content)
- sheet_token = (
- data.get("data", {}).get("block", {}).get("sheet", {}).get("token", "")
- )
+ sheet_token = data.get("data", {}).get("block", {}).get("sheet", {}).get("token", "")
if not sheet_token:
return None
@@ -618,9 +672,7 @@ class FeishuParser(BaseParser):
# Read cell data and trim empty trailing columns
try:
- rows = self._read_sheet_range(
- spreadsheet_token, sheet_id, max_rows=100, max_cols=26
- )
+ rows = self._read_sheet_range(spreadsheet_token, sheet_id, max_rows=100, max_cols=26)
if rows:
rows = self._trim_empty_columns(rows)
if rows:
@@ -666,9 +718,7 @@ class FeishuParser(BaseParser):
title = meta_response.data.spreadsheet.title or title
# Get sheet list
- sheets_request = (
- QuerySpreadsheetSheetRequest.builder().spreadsheet_token(token).build()
- )
+ sheets_request = QuerySpreadsheetSheetRequest.builder().spreadsheet_token(token).build()
sheets_response = client.sheets.v3.spreadsheet_sheet.query(sheets_request)
if not sheets_response.success():
raise RuntimeError(
@@ -736,9 +786,7 @@ class FeishuParser(BaseParser):
data = json.loads(response.raw.content)
values = data.get("data", {}).get("valueRange", {}).get("values", [])
- return [
- [str(cell) if cell is not None else "" for cell in row] for row in values
- ]
+ return [[str(cell) if cell is not None else "" for cell in row] for row in values]
@staticmethod
def _col_number_to_letter(n: int) -> str:
@@ -775,10 +823,7 @@ class FeishuParser(BaseParser):
table_name = table.name or table_id
fields_request = (
- ListAppTableFieldRequest.builder()
- .app_token(app_token)
- .table_id(table_id)
- .build()
+ ListAppTableFieldRequest.builder().app_token(app_token).table_id(table_id).build()
)
fields_response = client.bitable.v1.app_table_field.list(fields_request)
field_names: List[str] = []
@@ -798,9 +843,7 @@ class FeishuParser(BaseParser):
)
if page_token:
builder = builder.page_token(page_token)
- records_response = client.bitable.v1.app_table_record.list(
- builder.build()
- )
+ records_response = client.bitable.v1.app_table_record.list(builder.build())
if not records_response.success():
break
items = records_response.data.items or []
diff --git a/openviking/parse/parsers/html.py b/openviking/parse/parsers/html.py
index deaf0a86e..f1fc737e9 100644
--- a/openviking/parse/parsers/html.py
+++ b/openviking/parse/parsers/html.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
HTML and URL parser for OpenViking.
diff --git a/openviking/parse/parsers/legacy_doc.py b/openviking/parse/parsers/legacy_doc.py
index 95b770ae8..e30740e5d 100644
--- a/openviking/parse/parsers/legacy_doc.py
+++ b/openviking/parse/parsers/legacy_doc.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Legacy Word document (.doc) parser for OpenViking.
@@ -19,7 +19,7 @@ from openviking_cli.utils.logger import get_logger
logger = get_logger(__name__)
- # Max stream size to read (50MB) — prevents DoS from crafted files
+# Max stream size to read (50MB) — prevents DoS from crafted files
_MAX_STREAM_SIZE = 50 * 1024 * 1024
# Max character count sanity cap for ccpText
_MAX_CCP_TEXT = 10_000_000
@@ -154,9 +154,7 @@ class LegacyDocParser(BaseParser):
if fc_clx <= 0 or lcb_clx <= 0 or fc_clx + lcb_clx > len(table_data):
return self._simple_text_extract(word_doc, ccp_text)
- return self._extract_via_clx(
- word_doc, table_data, fc_clx, lcb_clx, ccp_text
- )
+ return self._extract_via_clx(word_doc, table_data, fc_clx, lcb_clx, ccp_text)
def _simple_text_extract(self, word_doc: bytes, ccp_text: int) -> str:
"""
@@ -177,7 +175,10 @@ class LegacyDocParser(BaseParser):
raw = word_doc[text_start:end]
text = raw.decode("utf-16-le", errors="replace")
# Sanity: if mostly printable, it's likely correct
- if sum(1 for c in text[:200] if c.isprintable() or c in "\n\r\t") > len(text[:200]) * 0.5:
+ if (
+ sum(1 for c in text[:200] if c.isprintable() or c in "\n\r\t")
+ > len(text[:200]) * 0.5
+ ):
return self._clean_word_text(text)
# Fall back to CP1252 single-byte
@@ -277,7 +278,9 @@ class LegacyDocParser(BaseParser):
raw = word_doc[byte_offset:byte_end]
text_parts.append(self._decode_cp1252(raw))
else:
- logger.warning(f"Piece {i} extends beyond stream ({byte_end} > {len(word_doc)})")
+ logger.warning(
+ f"Piece {i} extends beyond stream ({byte_end} > {len(word_doc)})"
+ )
else:
# UTF-16LE
byte_offset = fc_real
@@ -286,7 +289,9 @@ class LegacyDocParser(BaseParser):
raw = word_doc[byte_offset:byte_end]
text_parts.append(raw.decode("utf-16-le", errors="replace"))
else:
- logger.warning(f"Piece {i} extends beyond stream ({byte_end} > {len(word_doc)})")
+ logger.warning(
+ f"Piece {i} extends beyond stream ({byte_end} > {len(word_doc)})"
+ )
chars_extracted += piece_char_count
@@ -305,7 +310,7 @@ class LegacyDocParser(BaseParser):
"""Normalize Word control characters to readable equivalents."""
text = text.replace("\r\n", "\n").replace("\r", "\n")
# \x07 = cell/row end, \x0B = soft line break, \x0C = section break
- text = text.replace("\x07", "\t").replace("\x0B", "\n").replace("\x0C", "\n\n")
+ text = text.replace("\x07", "\t").replace("\x0b", "\n").replace("\x0c", "\n\n")
return text
def _fallback_extract(self, path: Path) -> str:
diff --git a/openviking/parse/parsers/markdown.py b/openviking/parse/parsers/markdown.py
index 7ded6c158..772a86445 100644
--- a/openviking/parse/parsers/markdown.py
+++ b/openviking/parse/parsers/markdown.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Markdown parser for OpenViking (v5.0).
diff --git a/openviking/parse/parsers/media/__init__.py b/openviking/parse/parsers/media/__init__.py
index 9f58977f4..965e29dcb 100644
--- a/openviking/parse/parsers/media/__init__.py
+++ b/openviking/parse/parsers/media/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from .audio import AudioParser
from .image import ImageParser
diff --git a/openviking/parse/parsers/media/audio.py b/openviking/parse/parsers/media/audio.py
index 52da25806..09edcb7a4 100644
--- a/openviking/parse/parsers/media/audio.py
+++ b/openviking/parse/parsers/media/audio.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Audio parser - Future implementation.
diff --git a/openviking/parse/parsers/media/constants.py b/openviking/parse/parsers/media/constants.py
index f8bc96cf2..55c59695b 100644
--- a/openviking/parse/parsers/media/constants.py
+++ b/openviking/parse/parsers/media/constants.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Constants for media parsers."""
# Image extensions supported by ImageParser
diff --git a/openviking/parse/parsers/media/image.py b/openviking/parse/parsers/media/image.py
index b35e7ed66..854e5cb39 100644
--- a/openviking/parse/parsers/media/image.py
+++ b/openviking/parse/parsers/media/image.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Media parser interfaces for OpenViking - Future expansion.
diff --git a/openviking/parse/parsers/media/utils.py b/openviking/parse/parsers/media/utils.py
index 7e8ec8ddf..86fd066e2 100644
--- a/openviking/parse/parsers/media/utils.py
+++ b/openviking/parse/parsers/media/utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Media-related utilities for OpenViking."""
import asyncio
diff --git a/openviking/parse/parsers/media/video.py b/openviking/parse/parsers/media/video.py
index fa98445c6..87f700bd0 100644
--- a/openviking/parse/parsers/media/video.py
+++ b/openviking/parse/parsers/media/video.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Video parser - Future implementation.
diff --git a/openviking/parse/parsers/pdf.py b/openviking/parse/parsers/pdf.py
index 382213e99..cb4916615 100644
--- a/openviking/parse/parsers/pdf.py
+++ b/openviking/parse/parsers/pdf.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
PDF parser for OpenViking.
diff --git a/openviking/parse/parsers/powerpoint.py b/openviking/parse/parsers/powerpoint.py
index a33a1cfca..c4307dc43 100644
--- a/openviking/parse/parsers/powerpoint.py
+++ b/openviking/parse/parsers/powerpoint.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
PowerPoint (.pptx) parser for OpenViking.
diff --git a/openviking/parse/parsers/text.py b/openviking/parse/parsers/text.py
index 7ad5b75cd..6e2515038 100644
--- a/openviking/parse/parsers/text.py
+++ b/openviking/parse/parsers/text.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Plain text parser for OpenViking.
diff --git a/openviking/parse/parsers/upload_utils.py b/openviking/parse/parsers/upload_utils.py
index d18701735..d4139f6c5 100644
--- a/openviking/parse/parsers/upload_utils.py
+++ b/openviking/parse/parsers/upload_utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Shared upload utilities for directory and file uploading to VikingFS."""
import asyncio
diff --git a/openviking/parse/parsers/word.py b/openviking/parse/parsers/word.py
index 35b0f426c..dc2a757c7 100644
--- a/openviking/parse/parsers/word.py
+++ b/openviking/parse/parsers/word.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Word document (.docx) parser for OpenViking.
diff --git a/openviking/parse/parsers/zip_parser.py b/openviking/parse/parsers/zip_parser.py
index ada2f8443..3418770ec 100644
--- a/openviking/parse/parsers/zip_parser.py
+++ b/openviking/parse/parsers/zip_parser.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
ZIP archive parser for OpenViking.
diff --git a/openviking/parse/registry.py b/openviking/parse/registry.py
index 8da983ddf..add62ddb1 100644
--- a/openviking/parse/registry.py
+++ b/openviking/parse/registry.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Parser registry for OpenViking.
@@ -19,14 +19,14 @@ from openviking.parse.parsers.excel import ExcelParser
# Import will be handled dynamically to avoid dependency issues
from openviking.parse.parsers.html import HTMLParser
+
+# Import markitdown-inspired parsers
+from openviking.parse.parsers.legacy_doc import LegacyDocParser
from openviking.parse.parsers.markdown import MarkdownParser
from openviking.parse.parsers.media import AudioParser, ImageParser, VideoParser
from openviking.parse.parsers.pdf import PDFParser
from openviking.parse.parsers.powerpoint import PowerPointParser
from openviking.parse.parsers.text import TextParser
-
-# Import markitdown-inspired parsers
-from openviking.parse.parsers.legacy_doc import LegacyDocParser
from openviking.parse.parsers.word import WordParser
from openviking.parse.parsers.zip_parser import ZipParser
diff --git a/openviking/parse/resource_detector/__init__.py b/openviking/parse/resource_detector/__init__.py
index 2a6416107..8b46d8ecf 100644
--- a/openviking/parse/resource_detector/__init__.py
+++ b/openviking/parse/resource_detector/__init__.py
@@ -1,3 +1,3 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Detect resource type and understand the content before process."""
diff --git a/openviking/parse/resource_detector/detect_info.py b/openviking/parse/resource_detector/detect_info.py
index 30135cd93..3b3106122 100644
--- a/openviking/parse/resource_detector/detect_info.py
+++ b/openviking/parse/resource_detector/detect_info.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Detect resource type and understand the content before process.
diff --git a/openviking/parse/resource_detector/recursive.py b/openviking/parse/resource_detector/recursive.py
index 819b3465d..236633478 100644
--- a/openviking/parse/resource_detector/recursive.py
+++ b/openviking/parse/resource_detector/recursive.py
@@ -1,2 +1,2 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
diff --git a/openviking/parse/resource_detector/size.py b/openviking/parse/resource_detector/size.py
index 819b3465d..236633478 100644
--- a/openviking/parse/resource_detector/size.py
+++ b/openviking/parse/resource_detector/size.py
@@ -1,2 +1,2 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
diff --git a/openviking/parse/resource_detector/visit.py b/openviking/parse/resource_detector/visit.py
index 819b3465d..236633478 100644
--- a/openviking/parse/resource_detector/visit.py
+++ b/openviking/parse/resource_detector/visit.py
@@ -1,2 +1,2 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
diff --git a/openviking/parse/tree_builder.py b/openviking/parse/tree_builder.py
index deea5efc0..6f133f75c 100644
--- a/openviking/parse/tree_builder.py
+++ b/openviking/parse/tree_builder.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Tree Builder for OpenViking.
diff --git a/openviking/parse/vlm.py b/openviking/parse/vlm.py
index 265223d2c..589e81eb9 100644
--- a/openviking/parse/vlm.py
+++ b/openviking/parse/vlm.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""VLM processor for image and table understanding."""
from dataclasses import dataclass
diff --git a/openviking/prompts/__init__.py b/openviking/prompts/__init__.py
index c3b5e63d2..e1d569073 100644
--- a/openviking/prompts/__init__.py
+++ b/openviking/prompts/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Prompt template management for OpenViking."""
from .manager import get_llm_config, get_manager, render_prompt
diff --git a/openviking/prompts/manager.py b/openviking/prompts/manager.py
index 0bf032c8f..b8e155392 100644
--- a/openviking/prompts/manager.py
+++ b/openviking/prompts/manager.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Prompt template management for OpenViking."""
import threading
diff --git a/openviking/resource/__init__.py b/openviking/resource/__init__.py
index 702b79059..d61388c1a 100644
--- a/openviking/resource/__init__.py
+++ b/openviking/resource/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Resource monitoring and management module."""
from openviking.resource.watch_manager import WatchManager, WatchTask
diff --git a/openviking/resource/watch_manager.py b/openviking/resource/watch_manager.py
index 0bb826668..d65dcc7c2 100644
--- a/openviking/resource/watch_manager.py
+++ b/openviking/resource/watch_manager.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Resource monitoring task manager.
diff --git a/openviking/resource/watch_scheduler.py b/openviking/resource/watch_scheduler.py
index 7eff06129..fe151bb9a 100644
--- a/openviking/resource/watch_scheduler.py
+++ b/openviking/resource/watch_scheduler.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Resource watch scheduler.
diff --git a/openviking/retrieve/__init__.py b/openviking/retrieve/__init__.py
index b53140050..39f532b30 100644
--- a/openviking/retrieve/__init__.py
+++ b/openviking/retrieve/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Retrieval module for OpenViking.
diff --git a/openviking/retrieve/hierarchical_retriever.py b/openviking/retrieve/hierarchical_retriever.py
index c1e5be670..1fbe4d468 100644
--- a/openviking/retrieve/hierarchical_retriever.py
+++ b/openviking/retrieve/hierarchical_retriever.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Hierarchical retriever for OpenViking.
@@ -8,8 +8,8 @@ and rerank-based relevance scoring.
"""
import heapq
-import math
import logging
+import math
import time
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
@@ -297,8 +297,7 @@ class HierarchicalRetriever:
# Results from global search
default_scores = [
- s if math.isfinite(s) else 0.0
- for s in (r.get("_score", 0.0) for r in global_results)
+ s if math.isfinite(s) else 0.0 for s in (r.get("_score", 0.0) for r in global_results)
]
if self._rerank_client and mode == RetrieverMode.THINKING:
docs = [str(r.get("abstract", "")) for r in global_results]
@@ -439,8 +438,7 @@ class HierarchicalRetriever:
continue
query_scores = [
- s if math.isfinite(s) else 0.0
- for s in (r.get("_score", 0.0) for r in results)
+ s if math.isfinite(s) else 0.0 for s in (r.get("_score", 0.0) for r in results)
]
if self._rerank_client and mode == RetrieverMode.THINKING:
documents = [str(r.get("abstract", "")) for r in results]
diff --git a/openviking/retrieve/intent_analyzer.py b/openviking/retrieve/intent_analyzer.py
index abbef9686..e7550065d 100644
--- a/openviking/retrieve/intent_analyzer.py
+++ b/openviking/retrieve/intent_analyzer.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Intent analyzer for OpenViking retrieval.
diff --git a/openviking/retrieve/memory_lifecycle.py b/openviking/retrieve/memory_lifecycle.py
index 4a35d656b..45d62da76 100644
--- a/openviking/retrieve/memory_lifecycle.py
+++ b/openviking/retrieve/memory_lifecycle.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Hotness scoring for cold/hot memory lifecycle management (#296).
Provides a pure function to compute a 0.0–1.0 hotness score based on
diff --git a/openviking/retrieve/retrieval_stats.py b/openviking/retrieve/retrieval_stats.py
index 7957a361d..191b9d371 100644
--- a/openviking/retrieve/retrieval_stats.py
+++ b/openviking/retrieve/retrieval_stats.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Thread-safe retrieval statistics accumulator.
Collects per-query metrics from the ``HierarchicalRetriever`` so that
diff --git a/openviking/server/__init__.py b/openviking/server/__init__.py
index ec11981d5..91a428deb 100644
--- a/openviking/server/__init__.py
+++ b/openviking/server/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""OpenViking HTTP Server module."""
diff --git a/openviking/server/api_keys.py b/openviking/server/api_keys.py
index 636656de8..e252454af 100644
--- a/openviking/server/api_keys.py
+++ b/openviking/server/api_keys.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""API Key management for OpenViking multi-tenant HTTP Server."""
import hmac
diff --git a/openviking/server/app.py b/openviking/server/app.py
index daa5de324..c70e8564e 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""FastAPI application for OpenViking HTTP Server."""
import asyncio
diff --git a/openviking/server/auth.py b/openviking/server/auth.py
index f7d897901..32159a9f7 100644
--- a/openviking/server/auth.py
+++ b/openviking/server/auth.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Authentication and authorization middleware for OpenViking multi-tenant HTTP Server."""
import hmac
diff --git a/openviking/server/bootstrap.py b/openviking/server/bootstrap.py
index 9362001c8..3ec355d59 100644
--- a/openviking/server/bootstrap.py
+++ b/openviking/server/bootstrap.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Bootstrap script for OpenViking HTTP Server."""
import argparse
diff --git a/openviking/server/config.py b/openviking/server/config.py
index 5995876f4..5e68f1d58 100644
--- a/openviking/server/config.py
+++ b/openviking/server/config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Server configuration for OpenViking HTTP Server."""
import sys
diff --git a/openviking/server/dependencies.py b/openviking/server/dependencies.py
index fc169a067..c99564acb 100644
--- a/openviking/server/dependencies.py
+++ b/openviking/server/dependencies.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Dependency injection for OpenViking HTTP Server."""
from typing import Optional
diff --git a/openviking/server/identity.py b/openviking/server/identity.py
index e39cb6010..0fae4a328 100644
--- a/openviking/server/identity.py
+++ b/openviking/server/identity.py
@@ -1,10 +1,10 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Identity and role types for OpenViking multi-tenant HTTP Server."""
from dataclasses import dataclass, field
from enum import Enum
-from typing import List, Optional, Any
+from typing import Any, List, Optional
from openviking_cli.session.user_id import UserIdentifier
diff --git a/openviking/server/local_input_guard.py b/openviking/server/local_input_guard.py
index 9e490b46f..ee0e2d091 100644
--- a/openviking/server/local_input_guard.py
+++ b/openviking/server/local_input_guard.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Guards for local-path handling on the HTTP server."""
from __future__ import annotations
diff --git a/openviking/server/models.py b/openviking/server/models.py
index 445da590b..ce6f3a9b3 100644
--- a/openviking/server/models.py
+++ b/openviking/server/models.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Response models and error codes for OpenViking HTTP Server."""
from typing import Any, Dict, Optional
diff --git a/openviking/server/routers/__init__.py b/openviking/server/routers/__init__.py
index 54e75da4e..6c969a8c1 100644
--- a/openviking/server/routers/__init__.py
+++ b/openviking/server/routers/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""OpenViking HTTP Server routers."""
from openviking.server.routers.admin import router as admin_router
diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.py
index b768fe693..c4b338edb 100644
--- a/openviking/server/routers/admin.py
+++ b/openviking/server/routers/admin.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Admin endpoints for OpenViking multi-tenant HTTP Server."""
from fastapi import APIRouter, Path, Request
diff --git a/openviking/server/routers/content.py b/openviking/server/routers/content.py
index 2b8beb44f..d95fdeea0 100644
--- a/openviking/server/routers/content.py
+++ b/openviking/server/routers/content.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Content endpoints for OpenViking HTTP Server."""
import asyncio
@@ -52,6 +52,7 @@ async def read(
if text:
from openviking.session.memory.utils.content import deserialize_content
+
result = deserialize_content(text)
return Response(status="ok", result=result)
diff --git a/openviking/server/routers/debug.py b/openviking/server/routers/debug.py
index d31c22794..266f36efd 100644
--- a/openviking/server/routers/debug.py
+++ b/openviking/server/routers/debug.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Debug endpoints for OpenViking HTTP Server.
Provides debug API for system diagnostics.
diff --git a/openviking/server/routers/filesystem.py b/openviking/server/routers/filesystem.py
index 97b9297ff..b5dcdb379 100644
--- a/openviking/server/routers/filesystem.py
+++ b/openviking/server/routers/filesystem.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Filesystem endpoints for OpenViking HTTP Server."""
from typing import Optional
diff --git a/openviking/server/routers/metrics.py b/openviking/server/routers/metrics.py
index 16546e93f..cfe2ab813 100644
--- a/openviking/server/routers/metrics.py
+++ b/openviking/server/routers/metrics.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Prometheus metrics endpoint for OpenViking HTTP Server."""
from fastapi import APIRouter, Request
diff --git a/openviking/server/routers/observer.py b/openviking/server/routers/observer.py
index 8f29f5478..ef8e1ea3c 100644
--- a/openviking/server/routers/observer.py
+++ b/openviking/server/routers/observer.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Observer endpoints for OpenViking HTTP Server.
Provides observability API for monitoring component status.
diff --git a/openviking/server/routers/pack.py b/openviking/server/routers/pack.py
index 86ad726b4..8b70fa145 100644
--- a/openviking/server/routers/pack.py
+++ b/openviking/server/routers/pack.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Pack endpoints for OpenViking HTTP Server."""
from fastapi import APIRouter, Depends
diff --git a/openviking/server/routers/relations.py b/openviking/server/routers/relations.py
index b68035130..4aa75506e 100644
--- a/openviking/server/routers/relations.py
+++ b/openviking/server/routers/relations.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Relations endpoints for OpenViking HTTP Server."""
from typing import List, Union
diff --git a/openviking/server/routers/resources.py b/openviking/server/routers/resources.py
index 415776cab..f9c3275f1 100644
--- a/openviking/server/routers/resources.py
+++ b/openviking/server/routers/resources.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Resource endpoints for OpenViking HTTP Server."""
import time
diff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.py
index 6f6c2054d..bf346479f 100644
--- a/openviking/server/routers/search.py
+++ b/openviking/server/routers/search.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Search endpoints for OpenViking HTTP Server."""
import math
diff --git a/openviking/server/routers/sessions.py b/openviking/server/routers/sessions.py
index ee6a898c5..3ea057b72 100644
--- a/openviking/server/routers/sessions.py
+++ b/openviking/server/routers/sessions.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Sessions endpoints for OpenViking HTTP Server."""
import logging
diff --git a/openviking/server/routers/stats.py b/openviking/server/routers/stats.py
index 33f79197a..f636d07a9 100644
--- a/openviking/server/routers/stats.py
+++ b/openviking/server/routers/stats.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Memory health statistics endpoints for OpenViking HTTP Server."""
import logging
diff --git a/openviking/server/routers/system.py b/openviking/server/routers/system.py
index ba322b617..ba5bd4666 100644
--- a/openviking/server/routers/system.py
+++ b/openviking/server/routers/system.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""System endpoints for OpenViking HTTP Server."""
from typing import Optional
diff --git a/openviking/server/routers/tasks.py b/openviking/server/routers/tasks.py
index e165ad558..2c2222239 100644
--- a/openviking/server/routers/tasks.py
+++ b/openviking/server/routers/tasks.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Task tracking endpoints for OpenViking HTTP Server.
Provides observability for background operations (e.g. session commit
diff --git a/openviking/server/telemetry.py b/openviking/server/telemetry.py
index 196f09ebd..d51aa6f8c 100644
--- a/openviking/server/telemetry.py
+++ b/openviking/server/telemetry.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""HTTP router helpers for operation telemetry."""
from __future__ import annotations
diff --git a/openviking/service/__init__.py b/openviking/service/__init__.py
index c9d2f7006..46090c8fe 100644
--- a/openviking/service/__init__.py
+++ b/openviking/service/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Service layer for OpenViking.
diff --git a/openviking/service/core.py b/openviking/service/core.py
index f5e6905a9..e61483fe5 100644
--- a/openviking/service/core.py
+++ b/openviking/service/core.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
OpenViking Service Core.
@@ -21,7 +21,7 @@ from openviking.service.relation_service import RelationService
from openviking.service.resource_service import ResourceService
from openviking.service.search_service import SearchService
from openviking.service.session_service import SessionService
-from openviking.session import create_session_compressor, SessionCompressor
+from openviking.session import SessionCompressor, create_session_compressor
from openviking.storage import VikingDBManager
from openviking.storage.collection_schemas import init_context_collection
from openviking.storage.queuefs.queue_manager import QueueManager, init_queue_manager
diff --git a/openviking/service/debug_service.py b/openviking/service/debug_service.py
index 2718a67dd..cc84c8f0f 100644
--- a/openviking/service/debug_service.py
+++ b/openviking/service/debug_service.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Debug Service - provides system status query and health check.
"""
diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.py
index 066c43282..f6e763fdf 100644
--- a/openviking/service/fs_service.py
+++ b/openviking/service/fs_service.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
File System Service for OpenViking.
diff --git a/openviking/service/pack_service.py b/openviking/service/pack_service.py
index b7a7d4bca..014d2ecac 100644
--- a/openviking/service/pack_service.py
+++ b/openviking/service/pack_service.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Pack Service for OpenViking.
diff --git a/openviking/service/relation_service.py b/openviking/service/relation_service.py
index cb94451da..91b1ff949 100644
--- a/openviking/service/relation_service.py
+++ b/openviking/service/relation_service.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Relation Service for OpenViking.
diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.py
index 4f0001d3e..056a09fd0 100644
--- a/openviking/service/resource_service.py
+++ b/openviking/service/resource_service.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Resource Service for OpenViking.
diff --git a/openviking/service/search_service.py b/openviking/service/search_service.py
index 0e6744414..af2562dcf 100644
--- a/openviking/service/search_service.py
+++ b/openviking/service/search_service.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Search Service for OpenViking.
diff --git a/openviking/service/session_service.py b/openviking/service/session_service.py
index 0e23e10ac..d6272675e 100644
--- a/openviking/service/session_service.py
+++ b/openviking/service/session_service.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Session Service for OpenViking.
diff --git a/openviking/service/task_tracker.py b/openviking/service/task_tracker.py
index e001cccd5..f7cd437e1 100644
--- a/openviking/service/task_tracker.py
+++ b/openviking/service/task_tracker.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Async Task Tracker for OpenViking.
diff --git a/openviking/session/__init__.py b/openviking/session/__init__.py
index ae0973e21..8d87f4a58 100644
--- a/openviking/session/__init__.py
+++ b/openviking/session/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Session management module."""
from typing import Optional
diff --git a/openviking/session/compressor.py b/openviking/session/compressor.py
index 9af225686..e2e90be17 100644
--- a/openviking/session/compressor.py
+++ b/openviking/session/compressor.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Session Compressor for OpenViking.
diff --git a/openviking/session/compressor_v2.py b/openviking/session/compressor_v2.py
index 079ed84b5..816c65e68 100644
--- a/openviking/session/compressor_v2.py
+++ b/openviking/session/compressor_v2.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Session Compressor V2 for OpenViking.
@@ -7,7 +7,6 @@ Uses the new Memory Templating System with ReAct orchestrator.
Maintains the same interface as compressor.py for backward compatibility.
"""
-import os
from typing import List, Optional
from openviking.core.context import Context
@@ -53,7 +52,10 @@ class SessionCompressorV2:
viking_fs = get_viking_fs()
# Create context provider with messages (provider 负责加载 schema)
- from openviking.session.memory.session_extract_context_provider import SessionExtractContextProvider
+ from openviking.session.memory.session_extract_context_provider import (
+ SessionExtractContextProvider,
+ )
+
context_provider = SessionExtractContextProvider(
messages=messages,
latest_archive_overview=latest_archive_overview,
@@ -72,9 +74,7 @@ class SessionCompressorV2:
Always create new instance to avoid cross-request state pollution.
"""
return MemoryUpdater(
- registry=registry,
- vikingdb=self.vikingdb,
- transaction_handle=transaction_handle
+ registry=registry, vikingdb=self.vikingdb, transaction_handle=transaction_handle
)
async def extract_long_term_memories(
@@ -117,14 +117,13 @@ class SessionCompressorV2:
viking_fs = get_viking_fs()
lock_manager = None
transaction_handle = None
- if viking_fs and hasattr(viking_fs, 'agfs') and viking_fs.agfs:
+ if viking_fs and hasattr(viking_fs, "agfs") and viking_fs.agfs:
init_lock_manager(viking_fs.agfs)
lock_manager = get_lock_manager()
transaction_handle = lock_manager.create_handle()
else:
logger.warning("VikingFS or AGFS not available, running without lock mechanism")
-
try:
# 获取所有记忆 schema 目录并加锁(仅在有锁管理器时)
orchestrator = self._get_or_create_react(
@@ -141,7 +140,9 @@ class SessionCompressorV2:
continue
user_space = ctx.user.user_space_name() if ctx and ctx.user else "default"
agent_space = ctx.user.agent_space_name() if ctx and ctx.user else "default"
- dir_path = schema.directory.replace("{user_space}", user_space).replace("{agent_space}", agent_space)
+ dir_path = schema.directory.replace("{user_space}", user_space).replace(
+ "{agent_space}", agent_space
+ )
dir_path = viking_fs._uri_to_path(dir_path, ctx)
if dir_path not in memory_schema_dirs:
memory_schema_dirs.append(dir_path)
@@ -169,10 +170,10 @@ class SessionCompressorV2:
return []
# Convert to legacy format for logging and apply_operations
- if hasattr(operations, 'to_legacy_operations'):
+ if hasattr(operations, "to_legacy_operations"):
legacy = operations.to_legacy_operations()
- write_uris = legacy.get('write_uris', [])
- edit_uris = legacy.get('edit_uris', [])
+ write_uris = legacy.get("write_uris", [])
+ edit_uris = legacy.get("edit_uris", [])
else:
# Fallback for old format
write_uris = operations.write_uris
@@ -190,10 +191,13 @@ class SessionCompressorV2:
# Create extract context from messages
from openviking.session.memory.memory_updater import ExtractContext
+
extract_context = ExtractContext(messages)
# Apply operations
- result = await updater.apply_operations(operations, ctx, registry=registry, extract_context=extract_context)
+ result = await updater.apply_operations(
+ operations, ctx, registry=registry, extract_context=extract_context
+ )
logger.info(
f"Applied memory operations: written={len(result.written_uris)}, "
@@ -203,7 +207,10 @@ class SessionCompressorV2:
# Report telemetry stats (matching v1 pattern)
telemetry = get_current_telemetry()
- telemetry.set("memory.extract.candidates.total", len(result.written_uris) + len(result.edited_uris))
+ telemetry.set(
+ "memory.extract.candidates.total",
+ len(result.written_uris) + len(result.edited_uris),
+ )
telemetry.set("memory.extract.created", len(result.written_uris))
telemetry.set("memory.extract.merged", len(result.edited_uris))
telemetry.set("memory.extract.deleted", len(result.deleted_uris))
@@ -214,27 +221,33 @@ class SessionCompressorV2:
# Written memories
for uri in result.written_uris:
- contexts.append(Context(
- uri=uri,
- category="memory_write",
- context_type="memory",
- ))
+ contexts.append(
+ Context(
+ uri=uri,
+ category="memory_write",
+ context_type="memory",
+ )
+ )
# Edited memories
for uri in result.edited_uris:
- contexts.append(Context(
- uri=uri,
- category="memory_edit",
- context_type="memory",
- ))
+ contexts.append(
+ Context(
+ uri=uri,
+ category="memory_edit",
+ context_type="memory",
+ )
+ )
# Deleted memories
for uri in result.deleted_uris:
- contexts.append(Context(
- uri=uri,
- category="memory_delete",
- context_type="memory",
- ))
+ contexts.append(
+ Context(
+ uri=uri,
+ category="memory_delete",
+ context_type="memory",
+ )
+ )
return contexts
diff --git a/openviking/session/memory/__init__.py b/openviking/session/memory/__init__.py
index b4d20d944..120a11c48 100644
--- a/openviking/session/memory/__init__.py
+++ b/openviking/session/memory/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Memory Templating System for OpenViking.
@@ -7,15 +7,6 @@ This module provides a YAML-configurable memory templating system with
ReAct (Reasoning + Action) pattern for memory updates.
"""
-from openviking.session.memory.utils import (
- detect_language_from_conversation,
- generate_uri,
- is_uri_allowed,
- is_uri_allowed_for_schema,
- pretty_print_messages,
- resolve_all_operations,
- validate_uri_template,
-)
from openviking.session.memory.dataclass import (
MemoryData,
MemoryField,
@@ -23,20 +14,20 @@ from openviking.session.memory.dataclass import (
MemoryTypeSchema,
StructuredMemoryOperations,
)
-from openviking.session.memory.merge_op import MergeOp, FieldType, MemoryPatchHandler
from openviking.session.memory.extract_loop import (
ExtractLoop,
)
from openviking.session.memory.memory_type_registry import MemoryTypeRegistry
from openviking.session.memory.memory_updater import MemoryUpdater, MemoryUpdateResult
+from openviking.session.memory.merge_op import FieldType, MemoryPatchHandler, MergeOp
from openviking.session.memory.schema_model_generator import (
SchemaModelGenerator,
SchemaPromptGenerator,
)
from openviking.session.memory.tools import (
- MemorySearchTool,
MemoryLsTool,
MemoryReadTool,
+ MemorySearchTool,
MemoryTool,
add_tool_call_items_to_messages,
add_tool_call_pair_to_messages,
@@ -45,6 +36,15 @@ from openviking.session.memory.tools import (
list_tools,
register_tool,
)
+from openviking.session.memory.utils import (
+ detect_language_from_conversation,
+ generate_uri,
+ is_uri_allowed,
+ is_uri_allowed_for_schema,
+ pretty_print_messages,
+ resolve_all_operations,
+ validate_uri_template,
+)
__all__ = [
# Data structures
diff --git a/openviking/session/memory/core.py b/openviking/session/memory/core.py
index 96eb86413..eede6a206 100644
--- a/openviking/session/memory/core.py
+++ b/openviking/session/memory/core.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Extract Context Provider - 抽象接口
@@ -71,4 +71,4 @@ class ExtractContextProvider(ABC):
Returns:
需要参与的 MemoryTypeSchema 列表
"""
- pass
\ No newline at end of file
+ pass
diff --git a/openviking/session/memory/dataclass.py b/openviking/session/memory/dataclass.py
index b66f5d3aa..f47380694 100644
--- a/openviking/session/memory/dataclass.py
+++ b/openviking/session/memory/dataclass.py
@@ -1,25 +1,32 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Core domain data classes for memory system.
"""
import json
from datetime import datetime
-from typing import Any, Dict, List, Optional, Protocol, TypeVar, Union, get_type_hints, get_origin, get_args
+from typing import (
+ Any,
+ Dict,
+ List,
+ Optional,
+ Protocol,
+ TypeVar,
+ Union,
+ get_args,
+ get_origin,
+ get_type_hints,
+)
from pydantic import BaseModel, Field, model_validator
from openviking.session.memory.merge_op.base import (
FieldType,
MergeOp,
- SearchReplaceBlock,
- StrPatch,
- get_python_type_for_field,
)
-
-T = TypeVar('T')
+T = TypeVar("T")
# ============================================================================
@@ -43,10 +50,14 @@ class MemoryTypeSchema(BaseModel):
description: str = Field("", description="Type description")
fields: List[MemoryField] = Field(default_factory=list, description="Field definitions")
filename_template: str = Field("", description="Filename template")
- content_template: Optional[str] = Field(None, description="Content template (for template mode)")
+ content_template: Optional[str] = Field(
+ None, description="Content template (for template mode)"
+ )
directory: str = Field("", description="Directory path")
enabled: bool = Field(True, description="Whether this memory type is enabled")
- operation_mode: str = Field("upsert", description="Operation mode: 'upsert' (default), 'add_only', or 'update_only'")
+ operation_mode: str = Field(
+ "upsert", description="Operation mode: 'upsert' (default), 'add_only', or 'update_only'"
+ )
class MemoryData(BaseModel):
@@ -72,8 +83,6 @@ class MemoryData(BaseModel):
self.fields[field_name] = value
-
-
# ============================================================================
# Fault Tolerant Base Model (参考 vikingdb BaseModelCompat)
# ============================================================================
@@ -87,7 +96,7 @@ class FaultTolerantBaseModel(BaseModel):
使得模型可以接受 LLM 输出的不标准格式数据。
"""
- @model_validator(mode='before')
+ @model_validator(mode="before")
@classmethod
def values_fault_tolerance(cls, data: Dict[str, Any]) -> Dict[str, Any]:
"""在验证前对所有字段做容错处理"""
@@ -135,7 +144,7 @@ class FaultTolerantBaseModel(BaseModel):
elif isinstance(value, dict):
return json.dumps(value, ensure_ascii=False)
elif isinstance(value, (int, bool, float)):
- return f'{value}'
+ return f"{value}"
return str(value)
@classmethod
@@ -151,14 +160,14 @@ class FaultTolerantBaseModel(BaseModel):
origin_type = cls.get_origin_type(field_type)
# json_repair 会把 None 转换成 'None'
- if value == 'None' and origin_type is not str:
+ if value == "None" and origin_type is not str:
return None
if origin_type is str:
return cls.any_to_str(value)
elif origin_type is int:
if isinstance(value, str):
- if value is None or value == 'None':
+ if value is None or value == "None":
return 0
try:
return int(value)
@@ -166,7 +175,7 @@ class FaultTolerantBaseModel(BaseModel):
pass
elif origin_type is float:
if isinstance(value, str):
- if value is None or value == 'None':
+ if value is None or value == "None":
return 0.0
try:
return float(value)
@@ -210,7 +219,7 @@ class StructuredMemoryOperations(FaultTolerantBaseModel):
"""
reasoning: str = Field(
- '',
+ "",
description="reasoning",
)
write_uris: List[Any] = Field(
@@ -248,7 +257,7 @@ class StructuredMemoryOperations(FaultTolerantBaseModel):
"delete_uris": self.delete_uris,
}
- model_config = {'extra': 'ignore'}
+ model_config = {"extra": "ignore"}
# Backward compatibility alias
diff --git a/openviking/session/memory/extract_loop.py b/openviking/session/memory/extract_loop.py
index 1965747a3..5cc668bbd 100644
--- a/openviking/session/memory/extract_loop.py
+++ b/openviking/session/memory/extract_loop.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Simplified ReAct orchestrator for memory updates - single LLM call with tool use.
@@ -10,36 +10,30 @@ import asyncio
import json
from typing import Any, Dict, List, Optional, Set, Tuple
-from openviking.message import Message
from openviking.models.vlm.base import VLMBase
from openviking.server.identity import RequestContext
from openviking.session.memory.dataclass import MemoryOperations
-from openviking.session.memory.memory_type_registry import MemoryTypeRegistry
from openviking.session.memory.schema_model_generator import (
SchemaModelGenerator,
SchemaPromptGenerator,
)
from openviking.session.memory.tools import (
+ MEMORY_TOOLS_REGISTRY,
add_tool_call_pair_to_messages,
get_tool,
- get_tool_schemas,
- MEMORY_TOOLS_REGISTRY,
)
from openviking.session.memory.utils import (
parse_json_with_stability,
parse_memory_file_with_fields,
pretty_print_messages,
- truncate_content,
validate_operations_uris,
)
from openviking.storage.viking_fs import VikingFS, get_viking_fs
from openviking_cli.utils import get_logger
-from openviking_cli.utils.config import get_openviking_config
logger = get_logger(__name__)
-
class ExtractLoop:
"""
Simplified ReAct orchestrator for memory updates.
@@ -93,8 +87,6 @@ class ExtractLoop:
# Transaction handle for file locking
self._transaction_handle = None
-
-
async def run(self) -> Tuple[Optional[MemoryOperations], List[Dict[str, Any]]]:
"""
Run the simplified ReAct loop for memory updates.
@@ -118,41 +110,48 @@ class ExtractLoop:
# 预计算工具 schemas
allowed_tools = self.context_provider.get_tools()
- self._tool_schemas = [tool.to_schema() for tool in MEMORY_TOOLS_REGISTRY.values() if tool.name in allowed_tools]
+ self._tool_schemas = [
+ tool.to_schema()
+ for tool in MEMORY_TOOLS_REGISTRY.values()
+ if tool.name in allowed_tools
+ ]
# 预计算 expected_fields
- self._expected_fields = ['reasoning', 'edit_overview_uris', 'delete_uris']
+ self._expected_fields = ["reasoning", "edit_overview_uris", "delete_uris"]
for schema in schemas:
self._expected_fields.append(schema.memory_type)
# 预计算 operations_model
self._operations_model = self.schema_model_generator.create_structured_operations_model()
-
-
# Reset read files tracking for this run
self._read_files.clear()
# Build initial messages from provider
import json
+
schema_str = json.dumps(self._json_schema, ensure_ascii=False)
messages = []
# instruction() 返回字符串,需要包装成 message 格式
- messages.append({
- "role": "system",
- "content": self.context_provider.instruction(),
- })
- messages.append({
- "role":"system",
- "content":f"""
+ messages.append(
+ {
+ "role": "system",
+ "content": self.context_provider.instruction(),
+ }
+ )
+ messages.append(
+ {
+ "role": "system",
+ "content": f"""
## Output Format
See the complete JSON Schema below:
```json
{schema_str}
```
- """
- })
+ """,
+ }
+ )
await self._mark_cache_breakpoint(messages)
# Pre-fetch context via provider
@@ -173,16 +172,17 @@ See the complete JSON Schema below:
# If last iteration, add a message telling the model to return result directly
if is_last_iteration:
- messages.append({
- "role": "user",
- "content": "You have reached the maximum number of tool call iterations. Do not call any more tools - return your final result directly now."
- })
+ messages.append(
+ {
+ "role": "user",
+ "content": "You have reached the maximum number of tool call iterations. Do not call any more tools - return your final result directly now.",
+ }
+ )
# Call LLM with tools - model decides: tool calls OR final operations
pretty_print_messages(messages)
tool_calls, operations = await self._call_llm(messages, force_final=is_last_iteration)
-
if tool_calls:
await self._execute_tool_calls(messages, tool_calls, tools_used)
await self._mark_cache_breakpoint(messages)
@@ -207,7 +207,9 @@ See the complete JSON Schema below:
final_operations = operations
break
# If no tool calls either, continue to next iteration (don't break!)
- logger.warning(f"LLM returned neither tool calls nor operations (iteration {iteration}/{max_iterations})")
+ logger.warning(
+ f"LLM returned neither tool calls nor operations (iteration {iteration}/{max_iterations})"
+ )
# If it's the last iteration, use empty operations
if is_last_iteration:
final_operations = MemoryOperations()
@@ -215,14 +217,13 @@ See the complete JSON Schema below:
# Otherwise continue and try again
continue
-
if final_operations is None:
if iteration >= max_iterations:
raise RuntimeError(f"Reached {max_iterations} iterations without completion")
else:
raise RuntimeError("ReAct loop completed but no operations generated")
- logger.info(f'final_operations={final_operations.model_dump_json(indent=4)}')
+ logger.info(f"final_operations={final_operations.model_dump_json(indent=4)}")
return final_operations, tools_used
@@ -234,8 +235,7 @@ See the complete JSON Schema below:
return idx, tool_call, result
action_tasks = [
- execute_single_tool_call(idx, tool_call)
- for idx, tool_call in enumerate(tool_calls)
+ execute_single_tool_call(idx, tool_call) for idx, tool_call in enumerate(tool_calls)
]
results = await self._execute_in_parallel(action_tasks)
@@ -246,11 +246,13 @@ See the complete JSON Schema below:
logger.warning(f"Tool call {tool_call.name} has no arguments, skipping")
continue
- tools_used.append({
- "tool_name": tool_call.name,
- "params": tool_call.arguments,
- "result": result,
- })
+ tools_used.append(
+ {
+ "tool_name": tool_call.name,
+ "params": tool_call.arguments,
+ "result": result,
+ }
+ )
# Track read tool calls for refetch detection
if tool_call.name == "read" and tool_call.arguments.get("uri"):
@@ -316,15 +318,23 @@ See the complete JSON Schema below:
)
# print(f'response={response}')
# Log cache hit info
- if hasattr(response, 'usage') and response.usage:
+ if hasattr(response, "usage") and response.usage:
usage = response.usage
- prompt_tokens = usage.get('prompt_tokens', 0)
- cached_tokens = usage.get('prompt_tokens_details', {}).get('cached_tokens', 0) if isinstance(usage.get('prompt_tokens_details'), dict) else 0
+ prompt_tokens = usage.get("prompt_tokens", 0)
+ cached_tokens = (
+ usage.get("prompt_tokens_details", {}).get("cached_tokens", 0)
+ if isinstance(usage.get("prompt_tokens_details"), dict)
+ else 0
+ )
if prompt_tokens > 0:
cache_hit_rate = (cached_tokens / prompt_tokens) * 100
- logger.info(f"[KVCache] prompt_tokens={prompt_tokens}, cached_tokens={cached_tokens}, cache_hit_rate={cache_hit_rate:.1f}%")
+ logger.info(
+ f"[KVCache] prompt_tokens={prompt_tokens}, cached_tokens={cached_tokens}, cache_hit_rate={cache_hit_rate:.1f}%"
+ )
else:
- logger.info(f"[KVCache] prompt_tokens={prompt_tokens}, cached_tokens={cached_tokens}")
+ logger.info(
+ f"[KVCache] prompt_tokens={prompt_tokens}, cached_tokens={cached_tokens}"
+ )
# Case 1: LLM returned tool calls
if response.has_tool_calls:
@@ -349,7 +359,7 @@ See the complete JSON Schema below:
)
if error is not None:
- print(f'content={content}')
+ print(f"content={content}")
logger.warning(f"Failed to parse memory operations: {error}")
return (None, None)
@@ -357,11 +367,11 @@ See the complete JSON Schema below:
self._validate_operations(operations)
return (None, operations)
except Exception as e:
- print(f'Error parsing operations: {e}')
+ print(f"Error parsing operations: {e}")
logger.warning(f"Unexpected error parsing memory operations: {e}")
# Case 3: No tool calls and no parsable operations
- print('No tool calls or operations parsed')
+ print("No tool calls or operations parsed")
return (None, None)
async def _execute_tool(
@@ -378,10 +388,8 @@ See the complete JSON Schema below:
# 创建 ToolContext
from openviking.server.identity import ToolContext
- tool_ctx = ToolContext(
- request_ctx=self.ctx,
- transaction_handle=self._transaction_handle
- )
+
+ tool_ctx = ToolContext(request_ctx=self.ctx, transaction_handle=self._transaction_handle)
try:
result = await tool.execute(self.viking_fs, tool_ctx, **tool_call.arguments)
@@ -402,7 +410,7 @@ See the complete JSON Schema below:
operations: MemoryOperations,
) -> List[str]:
"""Check if write operations target existing files that weren't read during ReAct."""
- memory_type_fields = getattr(operations, '_memory_type_fields', None)
+ memory_type_fields = getattr(operations, "_memory_type_fields", None)
if not memory_type_fields:
return []
@@ -418,9 +426,11 @@ See the complete JSON Schema below:
items = value if isinstance(value, list) else [value]
for item in items:
# Convert to dict
- item_dict = dict(item) if hasattr(item, 'model_dump') else dict(item)
+ item_dict = dict(item) if hasattr(item, "model_dump") else dict(item)
try:
- uri = resolve_flat_model_uri(item_dict, registry, "default", "default", memory_type=field_name)
+ uri = resolve_flat_model_uri(
+ item_dict, registry, "default", "default", memory_type=field_name
+ )
except Exception as e:
logger.warning(f"Failed to resolve URI for {item}: {e}")
continue
@@ -464,10 +474,12 @@ See the complete JSON Schema below:
logger.warning(f"Failed to refetch {uri}: {e}")
# Add reminder message for the model
- messages.append({
- "role": "user",
- "content": "Note: The files above were automatically read because they exist and you didn't read them before deciding to write. Please consider the existing content when making write decisions. You can now output updated operations."
- })
+ messages.append(
+ {
+ "role": "user",
+ "content": "Note: The files above were automatically read because they exist and you didn't read them before deciding to write. Please consider the existing content when making write decisions. You can now output updated operations.",
+ }
+ )
async def _mark_cache_breakpoint(self, messages):
# 支持 dict 消息和 object 消息
diff --git a/openviking/session/memory/memory_type_registry.py b/openviking/session/memory/memory_type_registry.py
index ef1b7afd3..3cd62ad25 100644
--- a/openviking/session/memory/memory_type_registry.py
+++ b/openviking/session/memory/memory_type_registry.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Memory type registry - loads YAML configurations.
"""
@@ -76,7 +76,9 @@ class MemoryTypeRegistry:
uris = []
for schema in self.list_all(include_disabled=False):
if schema.directory:
- dir_path = schema.directory.replace("{user_space}", user_space).replace("{agent_space}", agent_space)
+ dir_path = schema.directory.replace("{user_space}", user_space).replace(
+ "{agent_space}", agent_space
+ )
uris.append(dir_path)
return uris
@@ -152,7 +154,6 @@ class MemoryTypeRegistry:
)
-
def create_default_registry(schemas_dir: Optional[str] = None) -> MemoryTypeRegistry:
"""
Create a registry with built-in memory types.
diff --git a/openviking/session/memory/memory_updater.py b/openviking/session/memory/memory_updater.py
index 16dec5805..417d11547 100644
--- a/openviking/session/memory/memory_updater.py
+++ b/openviking/session/memory/memory_updater.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Memory updater - applies MemoryOperations directly.
@@ -22,7 +22,6 @@ from openviking.session.memory.utils import (
resolve_all_operations,
serialize_with_metadata,
)
-from openviking.session.memory.utils.uri import ResolvedOperation
from openviking.storage.viking_fs import get_viking_fs
from openviking_cli.exceptions import NotFoundError
from openviking_cli.utils import get_logger
@@ -32,6 +31,7 @@ logger = get_logger(__name__)
class ExtractContext:
"""Extract context for template rendering."""
+
def __init__(self, messages: List[Message]):
self.messages = messages
@@ -49,12 +49,12 @@ class ExtractContext:
# 解析所有范围/索引
ranges = []
- for part in ranges_str.split(','):
+ for part in ranges_str.split(","):
part = part.strip()
if not part:
continue
- if '-' in part:
- start, end = part.split('-')
+ if "-" in part:
+ start, end = part.split("-")
ranges.append((int(start), int(end)))
else:
# 单个索引转为相同起止范围
@@ -72,7 +72,7 @@ class ExtractContext:
for i, (start, end) in enumerate(ranges):
if start < 0 or end >= len(self.messages):
continue
- range_msgs = self.messages[start:end + 1]
+ range_msgs = self.messages[start : end + 1]
if i > 0:
prev_end = ranges[i - 1][1]
@@ -86,6 +86,7 @@ class ExtractContext:
class MessageRange:
"""Represents a range of messages for formatting."""
+
def __init__(self, elements: List[Message | str]):
self.elements = elements
@@ -104,7 +105,7 @@ class MessageRange:
for elem in self.elements:
if isinstance(elem, str):
continue
- if hasattr(elem, 'created_at') and elem.created_at:
+ if hasattr(elem, "created_at") and elem.created_at:
return elem.created_at.strftime("%Y-%m-%d")
return None
@@ -131,11 +132,7 @@ class MemoryUpdateResult:
self.errors.append((uri, error))
def has_changes(self) -> bool:
- return (
- len(self.written_uris) > 0
- or len(self.edited_uris) > 0
- or len(self.deleted_uris) > 0
- )
+ return len(self.written_uris) > 0 or len(self.edited_uris) > 0 or len(self.deleted_uris) > 0
def summary(self) -> str:
return (
@@ -146,8 +143,6 @@ class MemoryUpdateResult:
)
-
-
class MemoryUpdater:
"""
Applies MemoryOperations to storage.
@@ -156,7 +151,9 @@ class MemoryUpdater:
No function calls are used for write/edit/delete - these are executed directly.
"""
- def __init__(self, registry: Optional[MemoryTypeRegistry] = None, vikingdb=None, transaction_handle=None):
+ def __init__(
+ self, registry: Optional[MemoryTypeRegistry] = None, vikingdb=None, transaction_handle=None
+ ):
self._viking_fs = None
self._registry = registry
self._vikingdb = vikingdb
@@ -233,8 +230,10 @@ class MemoryUpdater:
)
result.add_written(resolved_op.uri)
except Exception as e:
- logger.info(f"Failed to write memory: {e}, op={resolved_op.model}, op type={type(resolved_op.model)}")
- if hasattr(resolved_op.model, 'model_dump'):
+ logger.info(
+ f"Failed to write memory: {e}, op={resolved_op.model}, op type={type(resolved_op.model)}"
+ )
+ if hasattr(resolved_op.model, "model_dump"):
logger.info(f"Op dump: {resolved_op.model.model_dump()}")
result.add_error(resolved_op.uri, e)
@@ -271,7 +270,14 @@ class MemoryUpdater:
logger.info(f"Memory operations applied: {result.summary()}")
return result
- async def _apply_write(self, flat_model: Any, uri: str, ctx: RequestContext, extract_context: Any = None, memory_type: str = None) -> None:
+ async def _apply_write(
+ self,
+ flat_model: Any,
+ uri: str,
+ ctx: RequestContext,
+ extract_context: Any = None,
+ memory_type: str = None,
+ ) -> None:
"""Apply write operation from a flat model."""
viking_fs = self._get_viking_fs()
@@ -299,11 +305,17 @@ class MemoryUpdater:
# 模板渲染逻辑
if schema.content_template:
try:
- rendered_content = self._render_content_template(schema.content_template, business_fields, extract_context=extract_context)
+ rendered_content = self._render_content_template(
+ schema.content_template,
+ business_fields,
+ extract_context=extract_context,
+ )
if rendered_content:
content = rendered_content
except Exception as e:
- logger.warning(f"Failed to render content template for memory type {memory_type_str}: {e}")
+ logger.warning(
+ f"Failed to render content template for memory type {memory_type_str}: {e}"
+ )
# 渲染失败时保留原始 content,确保写入操作继续进行
# Collect metadata - only include business fields (from schema, except content)
@@ -317,7 +329,9 @@ class MemoryUpdater:
await viking_fs.write_file(uri, full_content, ctx=ctx)
logger.debug(f"Written memory: {uri}")
- def _render_content_template(self, template: str, fields: Dict[str, Any], extract_context: Any = None) -> str:
+ def _render_content_template(
+ self, template: str, fields: Dict[str, Any], extract_context: Any = None
+ ) -> str:
"""
Render content template using Jinja2 template engine.
@@ -355,6 +369,7 @@ class MemoryUpdater:
def _is_patch_format(self, content: Any) -> bool:
"""Check if content is a patch format (StrPatch), not a complete replacement."""
from openviking.session.memory.merge_op.patch import StrPatch
+
return isinstance(content, StrPatch)
async def _apply_edit(self, flat_model: Any, uri: str, ctx: RequestContext) -> None:
@@ -420,6 +435,7 @@ class MemoryUpdater:
if "content" in model_dict and "content" not in field_schema_map:
from openviking.session.memory.merge_op import PatchOp
from openviking.session.memory.merge_op.base import FieldType
+
patch_value = model_dict["content"]
merge_op = PatchOp(FieldType.STRING)
new_plain_content = merge_op.apply(current_plain_content, patch_value)
@@ -446,7 +462,9 @@ class MemoryUpdater:
logger.warning(f"Memory not found for delete: {uri}")
# Idempotent - deleting non-existent file succeeds
- async def _apply_edit_overview(self, overview_model: Any, uri: str, ctx: RequestContext) -> None:
+ async def _apply_edit_overview(
+ self, overview_model: Any, uri: str, ctx: RequestContext
+ ) -> None:
"""
Apply edit operation for .overview.md file.
@@ -458,10 +476,10 @@ class MemoryUpdater:
viking_fs = self._get_viking_fs()
# Get overview value from model
- if hasattr(overview_model, 'overview'):
+ if hasattr(overview_model, "overview"):
overview_value = overview_model.overview
elif isinstance(overview_model, dict):
- overview_value = overview_model.get('overview')
+ overview_value = overview_model.get("overview")
else:
raise ValueError("overview_model must have overview field")
@@ -487,9 +505,9 @@ class MemoryUpdater:
new_overview = overview_value
elif isinstance(overview_value, dict):
# Dict format - convert to StrPatch if needed
- if 'blocks' in overview_value:
+ if "blocks" in overview_value:
# Already in StrPatch format
- blocks = [SearchReplaceBlock(**block) for block in overview_value['blocks']]
+ blocks = [SearchReplaceBlock(**block) for block in overview_value["blocks"]]
str_patch = StrPatch(blocks=blocks)
else:
# Unexpected format
@@ -563,6 +581,7 @@ class MemoryUpdater:
"""Print a diff of the memory edit using diff_match_patch."""
try:
from diff_match_patch import diff_match_patch
+
dmp = diff_match_patch()
# Compute character-level diff
@@ -577,7 +596,7 @@ class MemoryUpdater:
# ANSI styles
STYLE_DELETE = "\033[9m\033[31m" # 删除线 + 红色
- STYLE_INSERT = "\033[32m" # 绿色
+ STYLE_INSERT = "\033[32m" # 绿色
STYLE_RESET = "\033[0m"
for op, text in diffs:
diff --git a/openviking/session/memory/merge_op/__init__.py b/openviking/session/memory/merge_op/__init__.py
index e590d05b3..e81e5db63 100644
--- a/openviking/session/memory/merge_op/__init__.py
+++ b/openviking/session/memory/merge_op/__init__.py
@@ -1,25 +1,25 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Merge operation implementations.
"""
from openviking.session.memory.merge_op.base import (
+ FieldType,
MergeOp,
MergeOpBase,
- FieldType,
SearchReplaceBlock,
StrPatch,
)
-from openviking.session.memory.merge_op.patch import PatchOp
-from openviking.session.memory.merge_op.sum import SumOp
-from openviking.session.memory.merge_op.immutable import ImmutableOp
from openviking.session.memory.merge_op.factory import MergeOpFactory
+from openviking.session.memory.merge_op.immutable import ImmutableOp
+from openviking.session.memory.merge_op.patch import PatchOp
from openviking.session.memory.merge_op.patch_handler import (
MemoryPatchHandler,
PatchParseError,
apply_str_patch,
)
+from openviking.session.memory.merge_op.sum import SumOp
__all__ = [
"MergeOp",
diff --git a/openviking/session/memory/merge_op/base.py b/openviking/session/memory/merge_op/base.py
index 89c51ecd6..43f582b2f 100644
--- a/openviking/session/memory/merge_op/base.py
+++ b/openviking/session/memory/merge_op/base.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Merge operation base classes and registry.
"""
@@ -55,7 +55,7 @@ class SearchReplaceBlock(BaseModel):
search: str = Field(
...,
- description="Content to search for. ONLY include the EXACT lines you need to change - NEVER include the entire section. Example (WRONG): '## Melanie\\n- line1\\n- line2\\n[50 more lines]'. Example (CORRECT): '- Art can be in the most unlikely places, and love and acceptance really can be found everywhere'"
+ description="Content to search for. ONLY include the EXACT lines you need to change - NEVER include the entire section. Example (WRONG): '## Melanie\\n- line1\\n- line2\\n[50 more lines]'. Example (CORRECT): '- Art can be in the most unlikely places, and love and acceptance really can be found everywhere'",
)
replace: str = Field(..., description="Content to replace with")
start_line: Optional[int] = Field(None, description="Starting line number hint")
@@ -69,7 +69,7 @@ class StrPatch(BaseModel):
blocks: List[SearchReplaceBlock] = Field(
default_factory=list,
- description="List of SEARCH/REPLACE blocks to apply. PREFER direct string replacement over SEARCH/REPLACE when possible. When using SEARCH/REPLACE, only include the specific line(s) to change, never the entire section."
+ description="List of SEARCH/REPLACE blocks to apply. PREFER direct string replacement over SEARCH/REPLACE when possible. When using SEARCH/REPLACE, only include the specific line(s) to change, never the entire section.",
)
diff --git a/openviking/session/memory/merge_op/factory.py b/openviking/session/memory/merge_op/factory.py
index 0d048bece..4e34fe79c 100644
--- a/openviking/session/memory/merge_op/factory.py
+++ b/openviking/session/memory/merge_op/factory.py
@@ -1,15 +1,15 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Factory for creating MergeOp instances.
"""
from typing import TYPE_CHECKING
-from openviking.session.memory.merge_op.base import MergeOp, MergeOpBase, FieldType
+from openviking.session.memory.merge_op.base import FieldType, MergeOp, MergeOpBase
+from openviking.session.memory.merge_op.immutable import ImmutableOp
from openviking.session.memory.merge_op.patch import PatchOp
from openviking.session.memory.merge_op.sum import SumOp
-from openviking.session.memory.merge_op.immutable import ImmutableOp
if TYPE_CHECKING:
from openviking.session.memory.dataclass import MemoryField
@@ -40,7 +40,7 @@ class MergeOpFactory:
return PatchOp(field_type)
@staticmethod
- def from_field(field: 'MemoryField') -> MergeOpBase:
+ def from_field(field: "MemoryField") -> MergeOpBase:
"""Create a MergeOp instance from a MemoryField.
Args:
diff --git a/openviking/session/memory/merge_op/immutable.py b/openviking/session/memory/merge_op/immutable.py
index 67c24844a..413b7ca52 100644
--- a/openviking/session/memory/merge_op/immutable.py
+++ b/openviking/session/memory/merge_op/immutable.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Immutable merge operation - field cannot be changed once set.
"""
@@ -7,9 +7,9 @@ Immutable merge operation - field cannot be changed once set.
from typing import Any, Type
from openviking.session.memory.merge_op.base import (
+ FieldType,
MergeOp,
MergeOpBase,
- FieldType,
get_python_type_for_field,
)
diff --git a/openviking/session/memory/merge_op/patch.py b/openviking/session/memory/merge_op/patch.py
index c31b64055..d2f1b34f5 100644
--- a/openviking/session/memory/merge_op/patch.py
+++ b/openviking/session/memory/merge_op/patch.py
@@ -1,17 +1,17 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Patch merge operation - SEARCH/REPLACE for strings, direct replace for others.
"""
-from typing import Any, Type, TYPE_CHECKING
+from typing import TYPE_CHECKING, Any, Type
from openviking.session.memory.merge_op.base import (
+ FieldType,
MergeOp,
MergeOpBase,
- FieldType,
- StrPatch,
SearchReplaceBlock,
+ StrPatch,
get_python_type_for_field,
)
@@ -26,7 +26,7 @@ class PatchOp(MergeOpBase):
def __init__(self, field_type: FieldType):
self._field_type = field_type
- self._patch_handler: 'MemoryPatchHandler | None' = None
+ self._patch_handler: "MemoryPatchHandler | None" = None
def get_output_schema_type(self, field_type: FieldType) -> Type[Any]:
if field_type == FieldType.STRING:
diff --git a/openviking/session/memory/merge_op/patch_handler.py b/openviking/session/memory/merge_op/patch_handler.py
index aa5d44a7e..8ae43dbaa 100644
--- a/openviking/session/memory/merge_op/patch_handler.py
+++ b/openviking/session/memory/merge_op/patch_handler.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Patch handler for memory updates.
@@ -21,20 +21,20 @@ Enhanced features from RooCode:
import re
from dataclasses import dataclass
from enum import Enum
-from typing import Any, Dict, List, Optional, Tuple, TYPE_CHECKING
+from typing import TYPE_CHECKING, Any, Dict, List, Optional
-from openviking.session.memory.merge_op.base import SearchReplaceBlock, StrPatch
-from openviking.session.memory.merge_op.factory import MergeOpFactory
+from openviking.session.memory.merge_op.base import StrPatch
from openviking_cli.utils import get_logger
if TYPE_CHECKING:
- from openviking.session.memory.dataclass import MemoryField
+ pass
logger = get_logger(__name__)
class PatchParseError(Exception):
"""Error parsing patch content."""
+
pass
@@ -67,17 +67,17 @@ def levenshtein_distance(s1: str, s2: str) -> int:
def normalize_string(text: str) -> str:
"""Normalize string by handling smart quotes and special characters."""
replacements = {
- '\u2018': "'",
- '\u2019': "'",
- '\u201c': '"',
- '\u201d': '"',
- '\u00a0': ' ',
- '\u200b': '',
- '\u200c': '',
- '\u200d': '',
- '\u200e': '',
- '\u200f': '',
- '\ufeff': '',
+ "\u2018": "'",
+ "\u2019": "'",
+ "\u201c": '"',
+ "\u201d": '"',
+ "\u00a0": " ",
+ "\u200b": "",
+ "\u200c": "",
+ "\u200d": "",
+ "\u200e": "",
+ "\u200f": "",
+ "\ufeff": "",
}
for old, new in replacements.items():
text = text.replace(old, new)
@@ -102,10 +102,7 @@ def get_similarity(original: str, search: str) -> float:
def fuzzy_search(
- lines: List[str],
- search_chunk: str,
- start_index: int,
- end_index: int
+ lines: List[str], search_chunk: str, start_index: int, end_index: int
) -> Dict[str, Any]:
"""
Perform a "middle-out" search to find the slice most similar to search_chunk.
@@ -115,7 +112,7 @@ def fuzzy_search(
best_score = 0.0
best_match_index = -1
best_match_content = ""
- search_lines = search_chunk.split('\n')
+ search_lines = search_chunk.split("\n")
search_len = len(search_lines)
mid_point = (start_index + end_index) // 2
@@ -124,7 +121,7 @@ def fuzzy_search(
while left_index >= start_index or right_index <= end_index - search_len:
if left_index >= start_index:
- original_chunk = '\n'.join(lines[left_index:left_index + search_len])
+ original_chunk = "\n".join(lines[left_index : left_index + search_len])
similarity = get_similarity(original_chunk, search_chunk)
if similarity > best_score:
best_score = similarity
@@ -133,7 +130,7 @@ def fuzzy_search(
left_index -= 1
if right_index <= end_index - search_len:
- original_chunk = '\n'.join(lines[right_index:right_index + search_len])
+ original_chunk = "\n".join(lines[right_index : right_index + search_len])
similarity = get_similarity(original_chunk, search_chunk)
if similarity > best_score:
best_score = similarity
@@ -142,9 +139,9 @@ def fuzzy_search(
right_index += 1
return {
- 'bestScore': best_score,
- 'bestMatchIndex': best_match_index,
- 'bestMatchContent': best_match_content
+ "bestScore": best_score,
+ "bestMatchIndex": best_match_index,
+ "bestMatchContent": best_match_content,
}
@@ -155,9 +152,9 @@ def fuzzy_search(
def add_line_numbers(content: str, start_line: int = 1) -> str:
"""Add line numbers to content."""
- lines = content.split('\n')
+ lines = content.split("\n")
numbered_lines = [f"{start_line + i} | {line}" for i, line in enumerate(lines)]
- return '\n'.join(numbered_lines)
+ return "\n".join(numbered_lines)
def strip_line_numbers(content: str, aggressive: bool = False) -> str:
@@ -170,19 +167,19 @@ def strip_line_numbers(content: str, aggressive: bool = False) -> str:
"""
if aggressive:
# Aggressive: remove anything that looks like a line number at the start
- return re.sub(r'^\s*\d+\s*[|:]\s*', '', content, flags=re.MULTILINE)
+ return re.sub(r"^\s*\d+\s*[|:]\s*", "", content, flags=re.MULTILINE)
else:
# Standard: only strip "N | " format
- return re.sub(r'^\d+\s*\|\s*', '', content, flags=re.MULTILINE)
+ return re.sub(r"^\d+\s*\|\s*", "", content, flags=re.MULTILINE)
def every_line_has_line_numbers(content: str) -> bool:
"""Check if every line in content has a line number."""
- lines = content.split('\n')
+ lines = content.split("\n")
if not lines:
return False
# Check if all lines match the pattern "N | " at the start
- return all(re.match(r'^\d+\s*\|\s*', line) for line in lines)
+ return all(re.match(r"^\d+\s*\|\s*", line) for line in lines)
# ============================================================================
@@ -192,13 +189,14 @@ def every_line_has_line_numbers(content: str) -> bool:
def unescape_markers(content: str) -> str:
"""Unescape escaped markers in content."""
- return (content
- .replace(r'\<<<<<<<', '<<<<<<<')
- .replace(r'\=======', '=======')
- .replace(r'\>>>>>>>', '>>>>>>>')
- .replace(r'\-------', '-------')
- .replace(r'\:end_line:', ':end_line:')
- .replace(r'\:start_line:', ':start_line:'))
+ return (
+ content.replace(r"\<<<<<<<", "<<<<<<<")
+ .replace(r"\=======", "=======")
+ .replace(r"\>>>>>>>", ">>>>>>>")
+ .replace(r"\-------", "-------")
+ .replace(r"\:end_line:", ":end_line:")
+ .replace(r"\:start_line:", ":start_line:")
+ )
# ============================================================================
@@ -214,9 +212,9 @@ class State(Enum):
def validate_marker_sequencing(diff_content: str) -> Dict[str, Any]:
"""Validate the marker sequencing in diff content."""
- state = {'current': State.START, 'line': 0}
+ state = {"current": State.START, "line": 0}
- SEARCH_PATTERN = r'^<<<<<<< SEARCH>?$'
+ SEARCH_PATTERN = r"^<<<<<<< SEARCH>?$"
SEP = "======="
REPLACE = ">>>>>>> REPLACE"
SEARCH_PREFIX = "<<<<<<<"
@@ -224,8 +222,8 @@ def validate_marker_sequencing(diff_content: str) -> Dict[str, Any]:
def report_merge_conflict_error(found: str, _expected: str) -> Dict[str, Any]:
return {
- 'success': False,
- 'error': (
+ "success": False,
+ "error": (
f"ERROR: Special marker '{found}' found in your diff content at line {state['line']}:\n"
"\n"
f"When removing merge conflict markers like '{found}' from files, you MUST escape them\n"
@@ -246,13 +244,13 @@ def validate_marker_sequencing(diff_content: str) -> Dict[str, Any]:
f"\\{SEARCH_PREFIX}\n"
f"\\{SEP}\n"
f"\\{REPLACE}\n"
- )
+ ),
}
def report_invalid_diff_error(found: str, expected: str) -> Dict[str, Any]:
return {
- 'success': False,
- 'error': (
+ "success": False,
+ "error": (
f"ERROR: Diff block is malformed: marker '{found}' found in your diff content at line {state['line']}. "
f"Expected: {expected}\n"
"\n"
@@ -264,13 +262,13 @@ def validate_marker_sequencing(diff_content: str) -> Dict[str, Any]:
"=======\n"
"[new content to replace with]\n"
">>>>>>> REPLACE\n"
- )
+ ),
}
def report_line_marker_in_replace_error(marker: str) -> Dict[str, Any]:
return {
- 'success': False,
- 'error': (
+ "success": False,
+ "error": (
f"ERROR: Invalid line marker '{marker}' found in REPLACE section at line {state['line']}\n"
"\n"
"Line markers (:start_line: and :end_line:) are only allowed in SEARCH sections.\n"
@@ -290,42 +288,44 @@ def validate_marker_sequencing(diff_content: str) -> Dict[str, Any]:
":start_line:5 <-- Invalid location\n"
"replacement content\n"
">>>>>>> REPLACE\n"
- )
+ ),
}
- lines = diff_content.split('\n')
+ lines = diff_content.split("\n")
search_count = sum(1 for l in lines if re.match(SEARCH_PATTERN, l.strip()))
sep_count = sum(1 for l in lines if l.strip() == SEP)
replace_count = sum(1 for l in lines if l.strip() == REPLACE)
likely_bad_structure = search_count != replace_count or sep_count < search_count
- for line in diff_content.split('\n'):
- state['line'] += 1
+ for line in diff_content.split("\n"):
+ state["line"] += 1
marker = line.strip()
# Check for line markers in REPLACE sections (but allow escaped ones)
- if state['current'] == State.AFTER_SEPARATOR:
+ if state["current"] == State.AFTER_SEPARATOR:
if marker.startswith(":start_line:") and not line.strip().startswith(r"\:start_line:"):
return report_line_marker_in_replace_error(":start_line:")
if marker.startswith(":end_line:") and not line.strip().startswith(r"\:end_line:"):
return report_line_marker_in_replace_error(":end_line:")
- if state['current'] == State.START:
+ if state["current"] == State.START:
if marker == SEP:
- return (report_invalid_diff_error(SEP, "SEARCH")
- if likely_bad_structure
- else report_merge_conflict_error(SEP, "SEARCH"))
+ return (
+ report_invalid_diff_error(SEP, "SEARCH")
+ if likely_bad_structure
+ else report_merge_conflict_error(SEP, "SEARCH")
+ )
if marker == REPLACE:
return report_invalid_diff_error(REPLACE, "SEARCH")
if marker.startswith(REPLACE_PREFIX):
return report_merge_conflict_error(marker, "SEARCH")
if re.match(SEARCH_PATTERN, marker):
- state['current'] = State.AFTER_SEARCH
+ state["current"] = State.AFTER_SEARCH
elif marker.startswith(SEARCH_PREFIX):
return report_merge_conflict_error(marker, "SEARCH")
- elif state['current'] == State.AFTER_SEARCH:
+ elif state["current"] == State.AFTER_SEARCH:
if re.match(SEARCH_PATTERN, marker):
return report_invalid_diff_error("SEARCH", SEP)
if marker.startswith(SEARCH_PREFIX):
@@ -335,29 +335,31 @@ def validate_marker_sequencing(diff_content: str) -> Dict[str, Any]:
if marker.startswith(REPLACE_PREFIX):
return report_merge_conflict_error(marker, "SEARCH")
if marker == SEP:
- state['current'] = State.AFTER_SEPARATOR
+ state["current"] = State.AFTER_SEPARATOR
- elif state['current'] == State.AFTER_SEPARATOR:
+ elif state["current"] == State.AFTER_SEPARATOR:
if re.match(SEARCH_PATTERN, marker):
return report_invalid_diff_error("SEARCH", REPLACE)
if marker.startswith(SEARCH_PREFIX):
return report_merge_conflict_error(marker, REPLACE)
if marker == SEP:
- return (report_invalid_diff_error(SEP, REPLACE)
- if likely_bad_structure
- else report_merge_conflict_error(SEP, REPLACE))
+ return (
+ report_invalid_diff_error(SEP, REPLACE)
+ if likely_bad_structure
+ else report_merge_conflict_error(SEP, REPLACE)
+ )
if marker == REPLACE:
- state['current'] = State.START
+ state["current"] = State.START
elif marker.startswith(REPLACE_PREFIX):
return report_merge_conflict_error(marker, REPLACE)
- if state['current'] == State.START:
- return {'success': True}
+ if state["current"] == State.START:
+ return {"success": True}
else:
- expected = "=======" if state['current'] == State.AFTER_SEARCH else ">>>>>>> REPLACE"
+ expected = "=======" if state["current"] == State.AFTER_SEARCH else ">>>>>>> REPLACE"
return {
- 'success': False,
- 'error': f"ERROR: Unexpected end of sequence: Expected '{expected}' was not found."
+ "success": False,
+ "error": f"ERROR: Unexpected end of sequence: Expected '{expected}' was not found.",
}
@@ -369,6 +371,7 @@ def validate_marker_sequencing(diff_content: str) -> Dict[str, Any]:
@dataclass
class DiffResult:
"""Result of applying a diff."""
+
success: bool
content: Optional[str] = None
error: Optional[str] = None
@@ -415,20 +418,17 @@ class MultiSearchReplaceDiffStrategy:
"""
# Validate marker sequencing
valid_seq = validate_marker_sequencing(diff_content)
- if not valid_seq['success']:
- return DiffResult(success=False, error=valid_seq['error'])
+ if not valid_seq["success"]:
+ return DiffResult(success=False, error=valid_seq["error"])
# Parse diff blocks
matches = self._parse_diff_blocks(diff_content)
if not matches:
- return DiffResult(
- success=True,
- content=original_content
- )
+ return DiffResult(success=True, content=original_content)
# Detect line ending from original content
- line_ending = '\r\n' if '\r\n' in original_content else '\n'
- result_lines = re.split(r'\r?\n', original_content)
+ line_ending = "\r\n" if "\r\n" in original_content else "\n"
+ result_lines = re.split(r"\r?\n", original_content)
delta = 0
diff_results = []
applied_count = 0
@@ -436,18 +436,20 @@ class MultiSearchReplaceDiffStrategy:
# Sort replacements by start_line
replacements = [
{
- 'startLine': int(match.get('startLine', 0)),
- 'searchContent': match.get('searchContent', ''),
- 'replaceContent': match.get('replaceContent', '')
+ "startLine": int(match.get("startLine", 0)),
+ "searchContent": match.get("searchContent", ""),
+ "replaceContent": match.get("replaceContent", ""),
}
for match in matches
]
- replacements.sort(key=lambda x: x['startLine'])
+ replacements.sort(key=lambda x: x["startLine"])
for replacement in replacements:
- search_content = replacement['searchContent']
- replace_content = replacement['replaceContent']
- start_line = replacement['startLine'] + (replacement['startLine'] if replacement['startLine'] != 0 else 0)
+ search_content = replacement["searchContent"]
+ replace_content = replacement["replaceContent"]
+ start_line = replacement["startLine"] + (
+ replacement["startLine"] if replacement["startLine"] != 0 else 0
+ )
# Unescape markers
search_content = unescape_markers(search_content)
@@ -455,15 +457,15 @@ class MultiSearchReplaceDiffStrategy:
# Strip line numbers if present
has_all_line_numbers = (
- (every_line_has_line_numbers(search_content) and every_line_has_line_numbers(replace_content)) or
- (every_line_has_line_numbers(search_content) and replace_content.strip() == "")
- )
+ every_line_has_line_numbers(search_content)
+ and every_line_has_line_numbers(replace_content)
+ ) or (every_line_has_line_numbers(search_content) and replace_content.strip() == "")
if has_all_line_numbers and start_line == 0:
# Extract start line from first line
- first_line = search_content.split('\n')[0]
- if '|' in first_line:
- start_line = int(first_line.split('|')[0].strip())
+ first_line = search_content.split("\n")[0]
+ if "|" in first_line:
+ start_line = int(first_line.split("|")[0].strip())
if has_all_line_numbers:
search_content = strip_line_numbers(search_content)
@@ -471,38 +473,42 @@ class MultiSearchReplaceDiffStrategy:
# If search and replace are identical, treat as success (no changes needed)
if search_content == replace_content:
- diff_results.append({
- 'success': True,
- 'message': 'Search and replace content are identical - no changes needed'
- })
+ diff_results.append(
+ {
+ "success": True,
+ "message": "Search and replace content are identical - no changes needed",
+ }
+ )
continue
# Split content into lines
- search_lines = [] if search_content == "" else search_content.split('\n')
- replace_lines = [] if replace_content == "" else replace_content.split('\n')
+ search_lines = [] if search_content == "" else search_content.split("\n")
+ replace_lines = [] if replace_content == "" else replace_content.split("\n")
# Validate search content is not empty
if len(search_lines) == 0:
- diff_results.append({
- 'success': False,
- 'error': (
- "Empty search content is not allowed\n\n"
- "Debug Info:\n"
- "- Search content cannot be empty\n"
- "- For insertions, provide a specific line using :start_line: "
- "and include content to search for\n"
- "- For example, match a single line to insert before/after it"
- )
- })
+ diff_results.append(
+ {
+ "success": False,
+ "error": (
+ "Empty search content is not allowed\n\n"
+ "Debug Info:\n"
+ "- Search content cannot be empty\n"
+ "- For insertions, provide a specific line using :start_line: "
+ "and include content to search for\n"
+ "- For example, match a single line to insert before/after it"
+ ),
+ }
+ )
continue
- end_line = replacement['startLine'] + len(search_lines) - 1
+ end_line = replacement["startLine"] + len(search_lines) - 1
# Initialize search variables
match_index = -1
best_match_score = 0.0
best_match_content = ""
- search_chunk = '\n'.join(search_lines)
+ search_chunk = "\n".join(search_lines)
# Determine search bounds
search_start_index = 0
@@ -515,7 +521,7 @@ class MultiSearchReplaceDiffStrategy:
exact_end_index = exact_start_index + search_len - 1
# Try exact match first
- original_chunk = '\n'.join(result_lines[exact_start_index:exact_end_index + 1])
+ original_chunk = "\n".join(result_lines[exact_start_index : exact_end_index + 1])
similarity = get_similarity(original_chunk, search_chunk)
if similarity >= self.fuzzy_threshold:
match_index = exact_start_index
@@ -524,87 +530,106 @@ class MultiSearchReplaceDiffStrategy:
else:
# Set bounds for buffered search
search_start_index = max(0, start_line - (self.buffer_lines + 1))
- search_end_index = min(len(result_lines), start_line + len(search_lines) + self.buffer_lines)
+ search_end_index = min(
+ len(result_lines), start_line + len(search_lines) + self.buffer_lines
+ )
# If no match found yet, try middle-out search within bounds
if match_index == -1:
- fuzzy_result = fuzzy_search(result_lines, search_chunk, search_start_index, search_end_index)
- match_index = fuzzy_result['bestMatchIndex']
- best_match_score = fuzzy_result['bestScore']
- best_match_content = fuzzy_result['bestMatchContent']
+ fuzzy_result = fuzzy_search(
+ result_lines, search_chunk, search_start_index, search_end_index
+ )
+ match_index = fuzzy_result["bestMatchIndex"]
+ best_match_score = fuzzy_result["bestScore"]
+ best_match_content = fuzzy_result["bestMatchContent"]
# Try aggressive line number stripping as a fallback
if match_index == -1 or best_match_score < self.fuzzy_threshold:
aggressive_search_content = strip_line_numbers(search_content, aggressive=True)
aggressive_replace_content = strip_line_numbers(replace_content, aggressive=True)
- aggressive_search_lines = [] if aggressive_search_content == "" else aggressive_search_content.split('\n')
- aggressive_search_chunk = '\n'.join(aggressive_search_lines)
+ aggressive_search_lines = (
+ [] if aggressive_search_content == "" else aggressive_search_content.split("\n")
+ )
+ aggressive_search_chunk = "\n".join(aggressive_search_lines)
# Try middle-out search again with aggressive stripped content
- fuzzy_result = fuzzy_search(result_lines, aggressive_search_chunk, search_start_index, search_end_index)
- if fuzzy_result['bestMatchIndex'] != -1 and fuzzy_result['bestScore'] >= self.fuzzy_threshold:
- match_index = fuzzy_result['bestMatchIndex']
- best_match_score = fuzzy_result['bestScore']
- best_match_content = fuzzy_result['bestMatchContent']
+ fuzzy_result = fuzzy_search(
+ result_lines, aggressive_search_chunk, search_start_index, search_end_index
+ )
+ if (
+ fuzzy_result["bestMatchIndex"] != -1
+ and fuzzy_result["bestScore"] >= self.fuzzy_threshold
+ ):
+ match_index = fuzzy_result["bestMatchIndex"]
+ best_match_score = fuzzy_result["bestScore"]
+ best_match_content = fuzzy_result["bestMatchContent"]
# Replace with stripped versions
search_content = aggressive_search_content
replace_content = aggressive_replace_content
search_lines = aggressive_search_lines
- replace_lines = [] if replace_content == "" else replace_content.split('\n')
+ replace_lines = [] if replace_content == "" else replace_content.split("\n")
else:
# No match found with either method
if start_line and end_line:
- original_section = '\n\nOriginal Content:\n' + add_line_numbers(
- '\n'.join(result_lines[
- max(0, start_line - 1 - self.buffer_lines):
- min(len(result_lines), end_line + self.buffer_lines)
- ]),
- max(1, start_line - self.buffer_lines)
+ original_section = "\n\nOriginal Content:\n" + add_line_numbers(
+ "\n".join(
+ result_lines[
+ max(0, start_line - 1 - self.buffer_lines) : min(
+ len(result_lines), end_line + self.buffer_lines
+ )
+ ]
+ ),
+ max(1, start_line - self.buffer_lines),
)
else:
- original_section = '\n\nOriginal Content:\n' + add_line_numbers('\n'.join(result_lines))
+ original_section = "\n\nOriginal Content:\n" + add_line_numbers(
+ "\n".join(result_lines)
+ )
best_match_section = (
- '\n\nBest Match Found:\n' + add_line_numbers(best_match_content, match_index + 1)
+ "\n\nBest Match Found:\n"
+ + add_line_numbers(best_match_content, match_index + 1)
if best_match_content
- else '\n\nBest Match Found:\n(no match)'
+ else "\n\nBest Match Found:\n(no match)"
)
line_range = f" at line: {start_line}" if start_line else ""
- diff_results.append({
- 'success': False,
- 'error': (
- f"No sufficiently similar match found{line_range} "
- f"({int(best_match_score * 100)}% similar, "
- f"needs {int(self.fuzzy_threshold * 100)}%)\n\n"
- "Debug Info:\n"
- f"- Similarity Score: {int(best_match_score * 100)}%\n"
- f"- Required Threshold: {int(self.fuzzy_threshold * 100)}%\n"
- f"- Search Range: {f'starting at line {start_line}' if start_line else 'start to end'}\n"
- "- Tried both standard and aggressive line number stripping\n"
- "- Tip: Use read_file tool to get the latest content of the file before "
- "attempting to use apply_diff tool again, as file content may have changed\n\n"
- f"Search Content:\n{search_chunk}"
- f"{best_match_section}"
- f"{original_section}"
- )
- })
+ diff_results.append(
+ {
+ "success": False,
+ "error": (
+ f"No sufficiently similar match found{line_range} "
+ f"({int(best_match_score * 100)}% similar, "
+ f"needs {int(self.fuzzy_threshold * 100)}%)\n\n"
+ "Debug Info:\n"
+ f"- Similarity Score: {int(best_match_score * 100)}%\n"
+ f"- Required Threshold: {int(self.fuzzy_threshold * 100)}%\n"
+ f"- Search Range: {f'starting at line {start_line}' if start_line else 'start to end'}\n"
+ "- Tried both standard and aggressive line number stripping\n"
+ "- Tip: Use read_file tool to get the latest content of the file before "
+ "attempting to use apply_diff tool again, as file content may have changed\n\n"
+ f"Search Content:\n{search_chunk}"
+ f"{best_match_section}"
+ f"{original_section}"
+ ),
+ }
+ )
continue
# Get matched lines from original content
- matched_lines = result_lines[match_index:match_index + len(search_lines)]
+ matched_lines = result_lines[match_index : match_index + len(search_lines)]
# Get exact indentation of each line
original_indents = []
for line in matched_lines:
- match = re.match(r'^[\t ]*', line)
+ match = re.match(r"^[\t ]*", line)
original_indents.append(match.group(0) if match else "")
search_indents = []
for line in search_lines:
- match = re.match(r'^[\t ]*', line)
+ match = re.match(r"^[\t ]*", line)
search_indents.append(match.group(0) if match else "")
# Apply replacement while preserving exact indentation
@@ -624,29 +649,31 @@ class MultiSearchReplaceDiffStrategy:
search_indent = search_indents[0] if search_indents else ""
# Get indent from current replace line
- current_replace_match = re.match(r'^[\t ]*', line)
- current_replace_indent = current_replace_match.group(0) if current_replace_match else ""
+ current_replace_match = re.match(r"^[\t ]*", line)
+ current_replace_indent = (
+ current_replace_match.group(0) if current_replace_match else ""
+ )
# Calculate relative indent level (how much deeper/shallower this line is compared to search)
relative_level = len(current_replace_indent) - len(search_indent)
# Apply same relative level to matched indent
if relative_level >= 0:
- final_indent = matched_indent + current_replace_indent[len(search_indent):]
+ final_indent = matched_indent + current_replace_indent[len(search_indent) :]
else:
- final_indent = matched_indent[:max(0, len(matched_indent) + relative_level)]
+ final_indent = matched_indent[: max(0, len(matched_indent) + relative_level)]
# For empty lines, keep original indent with no content
if line.strip() == "":
indented_replace_lines.append(matched_indent)
else:
# Add line content (without its original indent, preserving internal whitespace)
- line_content = line.lstrip(' \t')
+ line_content = line.lstrip(" \t")
indented_replace_lines.append(final_indent + line_content)
# Construct final content
before_match = result_lines[:match_index]
- after_match = result_lines[match_index + len(search_lines):]
+ after_match = result_lines[match_index + len(search_lines) :]
result_lines = before_match + indented_replace_lines + after_match
delta = delta - len(matched_lines) + len(replace_lines)
applied_count += 1
@@ -654,8 +681,8 @@ class MultiSearchReplaceDiffStrategy:
final_content = line_ending.join(result_lines)
# Check if all results are successful (including no-change cases)
- all_successful = all(result.get('success', False) for result in diff_results)
- has_failures = any(not result.get('success', False) for result in diff_results)
+ all_successful = all(result.get("success", False) for result in diff_results)
+ has_failures = any(not result.get("success", False) for result in diff_results)
if applied_count == 0 and has_failures:
return DiffResult(success=False, fail_parts=diff_results)
@@ -666,9 +693,7 @@ class MultiSearchReplaceDiffStrategy:
return DiffResult(success=True, content=original_content, fail_parts=diff_results)
return DiffResult(
- success=True,
- content=final_content,
- fail_parts=diff_results if diff_results else None
+ success=True, content=final_content, fail_parts=diff_results if diff_results else None
)
def _parse_diff_blocks(self, diff_content: str) -> List[Dict[str, Any]]:
@@ -682,14 +707,14 @@ class MultiSearchReplaceDiffStrategy:
Returns list of dicts with keys: startLine, searchContent, replaceContent
"""
matches = []
- blocks = diff_content.split('<<<<<<< SEARCH')
+ blocks = diff_content.split("<<<<<<< SEARCH")
for block in blocks[1:]:
- if '=======' not in block or '>>>>>>> REPLACE' not in block:
+ if "=======" not in block or ">>>>>>> REPLACE" not in block:
continue
# Split by =======
- sep_parts = block.split('=======')
+ sep_parts = block.split("=======")
if len(sep_parts) < 2:
continue
@@ -697,40 +722,44 @@ class MultiSearchReplaceDiffStrategy:
after_sep = sep_parts[1]
# Split before_sep by -------
- dash_parts = before_sep.split('-------')
+ dash_parts = before_sep.split("-------")
if len(dash_parts) >= 2:
# v1 format: has -------
header = dash_parts[0]
- search_content = dash_parts[1].lstrip('\n').rstrip('\n') if len(dash_parts) > 1 else ''
+ search_content = (
+ dash_parts[1].lstrip("\n").rstrip("\n") if len(dash_parts) > 1 else ""
+ )
else:
# v2 format: no -------, entire before_sep is header + search content
# Extract :start_line: if present
- header = ''
- search_content = before_sep.lstrip('\n').rstrip('\n')
+ header = ""
+ search_content = before_sep.lstrip("\n").rstrip("\n")
# Check if first line is :start_line:
- lines = search_content.split('\n')
- if lines and lines[0].startswith(':start_line:'):
+ lines = search_content.split("\n")
+ if lines and lines[0].startswith(":start_line:"):
header = lines[0]
- search_content = '\n'.join(lines[1:])
+ search_content = "\n".join(lines[1:])
- replace_content = after_sep.split('>>>>>>> REPLACE')[0].lstrip('\n').rstrip('\n')
+ replace_content = after_sep.split(">>>>>>> REPLACE")[0].lstrip("\n").rstrip("\n")
# Extract start_line from header
start_line = 0
- for line in header.split('\n'):
- if line.startswith(':start_line:'):
+ for line in header.split("\n"):
+ if line.startswith(":start_line:"):
try:
- start_line = int(line.split(':')[1].strip())
+ start_line = int(line.split(":")[1].strip())
except:
pass
- matches.append({
- 'startLine': start_line,
- 'searchContent': search_content,
- 'replaceContent': replace_content
- })
+ matches.append(
+ {
+ "startLine": start_line,
+ "searchContent": search_content,
+ "replaceContent": replace_content,
+ }
+ )
return matches
@@ -758,8 +787,7 @@ class MemoryPatchHandler:
buffer_lines: Number of extra context lines to search (default 40)
"""
self._strategy = MultiSearchReplaceDiffStrategy(
- fuzzy_threshold=fuzzy_threshold,
- buffer_lines=buffer_lines
+ fuzzy_threshold=fuzzy_threshold, buffer_lines=buffer_lines
)
def apply_content_patch(self, original_content: str, patch: str) -> str:
@@ -792,8 +820,8 @@ class MemoryPatchHandler:
# First validate marker sequencing - raise PatchParseError for invalid patches
valid_seq = validate_marker_sequencing(patch)
- if not valid_seq['success']:
- raise PatchParseError(valid_seq['error'])
+ if not valid_seq["success"]:
+ raise PatchParseError(valid_seq["error"])
result = self._strategy.apply_diff(original_content, patch)
@@ -810,13 +838,12 @@ class MemoryPatchHandler:
try:
matches = self._strategy._parse_diff_blocks(patch)
if matches:
- return matches[-1].get('replaceContent', '')
+ return matches[-1].get("replaceContent", "")
except Exception:
pass
return patch
-
def apply_str_patch(original_content: str, patch: StrPatch) -> str:
"""Apply a StrPatch to original content.
@@ -836,37 +863,41 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
# Convert StrPatch blocks to internal match format
matches = []
for block in patch.blocks:
- matches.append({
- 'startLine': block.start_line or 0,
- 'searchContent': block.search,
- 'replaceContent': block.replace
- })
+ matches.append(
+ {
+ "startLine": block.start_line or 0,
+ "searchContent": block.search,
+ "replaceContent": block.replace,
+ }
+ )
if not matches:
return original_content
# Apply using the same logic as apply_diff, but with pre-parsed matches
# Detect line ending from original content
- line_ending = '\r\n' if '\r\n' in original_content else '\n'
- result_lines = re.split(r'\r?\n', original_content)
+ line_ending = "\r\n" if "\r\n" in original_content else "\n"
+ result_lines = re.split(r"\r?\n", original_content)
diff_results = []
applied_count = 0
# Sort replacements by start_line
replacements = [
{
- 'startLine': int(match.get('startLine', 0)),
- 'searchContent': match.get('searchContent', ''),
- 'replaceContent': match.get('replaceContent', '')
+ "startLine": int(match.get("startLine", 0)),
+ "searchContent": match.get("searchContent", ""),
+ "replaceContent": match.get("replaceContent", ""),
}
for match in matches
]
- replacements.sort(key=lambda x: x['startLine'])
+ replacements.sort(key=lambda x: x["startLine"])
for replacement in replacements:
- search_content = replacement['searchContent']
- replace_content = replacement['replaceContent']
- start_line = replacement['startLine'] + (replacement['startLine'] if replacement['startLine'] != 0 else 0)
+ search_content = replacement["searchContent"]
+ replace_content = replacement["replaceContent"]
+ start_line = replacement["startLine"] + (
+ replacement["startLine"] if replacement["startLine"] != 0 else 0
+ )
# Unescape markers
search_content = unescape_markers(search_content)
@@ -874,15 +905,15 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
# Strip line numbers if present
has_all_line_numbers = (
- (every_line_has_line_numbers(search_content) and every_line_has_line_numbers(replace_content)) or
- (every_line_has_line_numbers(search_content) and replace_content.strip() == "")
- )
+ every_line_has_line_numbers(search_content)
+ and every_line_has_line_numbers(replace_content)
+ ) or (every_line_has_line_numbers(search_content) and replace_content.strip() == "")
if has_all_line_numbers and start_line == 0:
# Extract start line from first line
- first_line = search_content.split('\n')[0]
- if '|' in first_line:
- start_line = int(first_line.split('|')[0].strip())
+ first_line = search_content.split("\n")[0]
+ if "|" in first_line:
+ start_line = int(first_line.split("|")[0].strip())
if has_all_line_numbers:
search_content = strip_line_numbers(search_content)
@@ -890,36 +921,40 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
# If search and replace are identical, treat as success (no changes needed)
if search_content == replace_content:
- diff_results.append({
- 'success': True,
- 'message': 'Search and replace content are identical - no changes needed'
- })
+ diff_results.append(
+ {
+ "success": True,
+ "message": "Search and replace content are identical - no changes needed",
+ }
+ )
continue
# Split content into lines
- search_lines = [] if search_content == "" else search_content.split('\n')
- replace_lines = [] if replace_content == "" else replace_content.split('\n')
+ search_lines = [] if search_content == "" else search_content.split("\n")
+ replace_lines = [] if replace_content == "" else replace_content.split("\n")
# Validate search content is not empty
if len(search_lines) == 0:
- diff_results.append({
- 'success': False,
- 'error': (
- "Empty search content is not allowed\n\n"
- "Debug Info:\n"
- "- Search content cannot be empty\n"
- "- For insertions, provide a specific line using :start_line: "
- "and include content to search for\n"
- "- For example, match a single line to insert before/after it"
- )
- })
+ diff_results.append(
+ {
+ "success": False,
+ "error": (
+ "Empty search content is not allowed\n\n"
+ "Debug Info:\n"
+ "- Search content cannot be empty\n"
+ "- For insertions, provide a specific line using :start_line: "
+ "and include content to search for\n"
+ "- For example, match a single line to insert before/after it"
+ ),
+ }
+ )
continue
# Initialize search variables
match_index = -1
best_match_score = 0.0
best_match_content = ""
- search_chunk = '\n'.join(search_lines)
+ search_chunk = "\n".join(search_lines)
# Determine search bounds
search_start_index = 0
@@ -932,7 +967,7 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
exact_end_index = exact_start_index + search_len - 1
# Try exact match first
- original_chunk = '\n'.join(result_lines[exact_start_index:exact_end_index + 1])
+ original_chunk = "\n".join(result_lines[exact_start_index : exact_end_index + 1])
similarity = get_similarity(original_chunk, search_chunk)
if similarity >= strategy.fuzzy_threshold:
match_index = exact_start_index
@@ -941,88 +976,107 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
else:
# Set bounds for buffered search
search_start_index = max(0, start_line - (strategy.buffer_lines + 1))
- search_end_index = min(len(result_lines), start_line + len(search_lines) + strategy.buffer_lines)
+ search_end_index = min(
+ len(result_lines), start_line + len(search_lines) + strategy.buffer_lines
+ )
# If no match found yet, try middle-out search within bounds
if match_index == -1:
- fuzzy_result = fuzzy_search(result_lines, search_chunk, search_start_index, search_end_index)
- match_index = fuzzy_result['bestMatchIndex']
- best_match_score = fuzzy_result['bestScore']
- best_match_content = fuzzy_result['bestMatchContent']
+ fuzzy_result = fuzzy_search(
+ result_lines, search_chunk, search_start_index, search_end_index
+ )
+ match_index = fuzzy_result["bestMatchIndex"]
+ best_match_score = fuzzy_result["bestScore"]
+ best_match_content = fuzzy_result["bestMatchContent"]
# Try aggressive line number stripping as a fallback
if match_index == -1 or best_match_score < strategy.fuzzy_threshold:
aggressive_search_content = strip_line_numbers(search_content, aggressive=True)
aggressive_replace_content = strip_line_numbers(replace_content, aggressive=True)
- aggressive_search_lines = [] if aggressive_search_content == "" else aggressive_search_content.split('\n')
- aggressive_search_chunk = '\n'.join(aggressive_search_lines)
+ aggressive_search_lines = (
+ [] if aggressive_search_content == "" else aggressive_search_content.split("\n")
+ )
+ aggressive_search_chunk = "\n".join(aggressive_search_lines)
# Try middle-out search again with aggressive stripped content
- fuzzy_result = fuzzy_search(result_lines, aggressive_search_chunk, search_start_index, search_end_index)
- if fuzzy_result['bestMatchIndex'] != -1 and fuzzy_result['bestScore'] >= strategy.fuzzy_threshold:
- match_index = fuzzy_result['bestMatchIndex']
- best_match_score = fuzzy_result['bestScore']
- best_match_content = fuzzy_result['bestMatchContent']
+ fuzzy_result = fuzzy_search(
+ result_lines, aggressive_search_chunk, search_start_index, search_end_index
+ )
+ if (
+ fuzzy_result["bestMatchIndex"] != -1
+ and fuzzy_result["bestScore"] >= strategy.fuzzy_threshold
+ ):
+ match_index = fuzzy_result["bestMatchIndex"]
+ best_match_score = fuzzy_result["bestScore"]
+ best_match_content = fuzzy_result["bestMatchContent"]
# Replace with stripped versions
search_content = aggressive_search_content
replace_content = aggressive_replace_content
search_lines = aggressive_search_lines
- replace_lines = [] if replace_content == "" else replace_content.split('\n')
+ replace_lines = [] if replace_content == "" else replace_content.split("\n")
else:
# No match found with either method
if start_line:
end_line = start_line + len(search_lines) - 1
- original_section = '\n\nOriginal Content:\n' + add_line_numbers(
- '\n'.join(result_lines[
- max(0, start_line - 1 - strategy.buffer_lines):
- min(len(result_lines), end_line + strategy.buffer_lines)
- ]),
- max(1, start_line - strategy.buffer_lines)
+ original_section = "\n\nOriginal Content:\n" + add_line_numbers(
+ "\n".join(
+ result_lines[
+ max(0, start_line - 1 - strategy.buffer_lines) : min(
+ len(result_lines), end_line + strategy.buffer_lines
+ )
+ ]
+ ),
+ max(1, start_line - strategy.buffer_lines),
)
else:
- original_section = '\n\nOriginal Content:\n' + add_line_numbers('\n'.join(result_lines))
+ original_section = "\n\nOriginal Content:\n" + add_line_numbers(
+ "\n".join(result_lines)
+ )
best_match_section = (
- '\n\nBest Match Found:\n' + add_line_numbers(best_match_content, match_index + 1)
+ "\n\nBest Match Found:\n"
+ + add_line_numbers(best_match_content, match_index + 1)
if best_match_content
- else '\n\nBest Match Found:\n(no match)'
+ else "\n\nBest Match Found:\n(no match)"
)
line_range = f" at line: {start_line}" if start_line else ""
- diff_results.append({
- 'success': False,
- 'error': (
- f"No sufficiently similar match found{line_range} "
- f"({int(best_match_score * 100)}% similar, "
- f"needs {int(strategy.fuzzy_threshold * 100)}%)\n\n"
- "Debug Info:\n"
- f"- Similarity Score: {int(best_match_score * 100)}%\n"
- f"- Required Threshold: {int(strategy.fuzzy_threshold * 100)}%\n"
- f"- Search Range: {f'starting at line {start_line}' if start_line else 'start to end'}\n"
- "- Tried both standard and aggressive line number stripping\n"
- "- Tip: Use read_file tool to get the latest content of the file before "
- "attempting to use apply_diff tool again, as file content may have changed\n\n"
- f"Search Content:\n{search_chunk}"
- f"{best_match_section}"
- f"{original_section}"
- )
- })
+ diff_results.append(
+ {
+ "success": False,
+ "error": (
+ f"No sufficiently similar match found{line_range} "
+ f"({int(best_match_score * 100)}% similar, "
+ f"needs {int(strategy.fuzzy_threshold * 100)}%)\n\n"
+ "Debug Info:\n"
+ f"- Similarity Score: {int(best_match_score * 100)}%\n"
+ f"- Required Threshold: {int(strategy.fuzzy_threshold * 100)}%\n"
+ f"- Search Range: {f'starting at line {start_line}' if start_line else 'start to end'}\n"
+ "- Tried both standard and aggressive line number stripping\n"
+ "- Tip: Use read_file tool to get the latest content of the file before "
+ "attempting to use apply_diff tool again, as file content may have changed\n\n"
+ f"Search Content:\n{search_chunk}"
+ f"{best_match_section}"
+ f"{original_section}"
+ ),
+ }
+ )
continue
# Get matched lines from original content
- matched_lines = result_lines[match_index:match_index + len(search_lines)]
+ matched_lines = result_lines[match_index : match_index + len(search_lines)]
# Get exact indentation of each line
original_indents = []
for line in matched_lines:
- match = re.match(r'^[\t ]*', line)
+ match = re.match(r"^[\t ]*", line)
original_indents.append(match.group(0) if match else "")
search_indents = []
for line in search_lines:
- match = re.match(r'^[\t ]*', line)
+ match = re.match(r"^[\t ]*", line)
search_indents.append(match.group(0) if match else "")
# Apply replacement while preserving exact indentation
@@ -1042,7 +1096,7 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
search_indent = search_indents[0] if search_indents else ""
# Get indent from current replace line
- current_replace_match = re.match(r'^[\t ]*', line)
+ current_replace_match = re.match(r"^[\t ]*", line)
current_replace_indent = current_replace_match.group(0) if current_replace_match else ""
# Calculate relative indent level (how much deeper/shallower this line is compared to search)
@@ -1050,38 +1104,37 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
# Apply same relative level to matched indent
if relative_level >= 0:
- final_indent = matched_indent + current_replace_indent[len(search_indent):]
+ final_indent = matched_indent + current_replace_indent[len(search_indent) :]
else:
- final_indent = matched_indent[:max(0, len(matched_indent) + relative_level)]
+ final_indent = matched_indent[: max(0, len(matched_indent) + relative_level)]
# For empty lines, keep original indent with no content
if line.strip() == "":
indented_replace_lines.append(matched_indent)
else:
# Add line content (without its original indent, preserving internal whitespace)
- line_content = line.lstrip(' \t')
+ line_content = line.lstrip(" \t")
indented_replace_lines.append(final_indent + line_content)
# Construct final content
before_match = result_lines[:match_index]
- after_match = result_lines[match_index + len(search_lines):]
+ after_match = result_lines[match_index + len(search_lines) :]
result_lines = before_match + indented_replace_lines + after_match
applied_count += 1
final_content = line_ending.join(result_lines)
# Check if all results are successful (including no-change cases)
- all_successful = all(result.get('success', False) for result in diff_results)
- has_failures = any(not result.get('success', False) for result in diff_results)
+ all_successful = all(result.get("success", False) for result in diff_results)
+ has_failures = any(not result.get("success", False) for result in diff_results)
if applied_count == 0 and has_failures:
# If failed, fall back to appending last replace content
- logger.warning(f"Patch application failed, falling back to append")
- last_replace = matches[-1].get('replaceContent', '') if matches else ''
+ logger.warning("Patch application failed, falling back to append")
+ last_replace = matches[-1].get("replaceContent", "") if matches else ""
return original_content + "\n" + last_replace
return final_content
# Import MergeOp here to avoid circular import
-from openviking.session.memory.merge_op.base import MergeOp
diff --git a/openviking/session/memory/merge_op/sum.py b/openviking/session/memory/merge_op/sum.py
index f92f0e7da..d5ab7f8fc 100644
--- a/openviking/session/memory/merge_op/sum.py
+++ b/openviking/session/memory/merge_op/sum.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Sum merge operation - numeric addition.
"""
@@ -7,9 +7,9 @@ Sum merge operation - numeric addition.
from typing import Any, Type
from openviking.session.memory.merge_op.base import (
+ FieldType,
MergeOp,
MergeOpBase,
- FieldType,
get_python_type_for_field,
)
diff --git a/openviking/session/memory/schema_model_generator.py b/openviking/session/memory/schema_model_generator.py
index 2e4d10e76..275ef0a8f 100644
--- a/openviking/session/memory/schema_model_generator.py
+++ b/openviking/session/memory/schema_model_generator.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Dynamic Pydantic model generator based on YAML schemas.
@@ -8,17 +8,14 @@ definitions, with discriminator support for polymorphic fields.
"""
import re
-from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple, Type, Union
from pydantic import BaseModel, Field, create_model
from pydantic.config import ConfigDict
-from typing_extensions import Annotated, Literal
from openviking.session.memory.dataclass import FaultTolerantBaseModel, MemoryTypeSchema
from openviking.session.memory.merge_op import MergeOp, MergeOpFactory
from openviking.session.memory.merge_op.base import FieldType, StrPatch, get_python_type_for_field
-from openviking.session.memory.memory_type_registry import MemoryTypeRegistry
from openviking_cli.utils import get_logger
logger = get_logger(__name__)
@@ -185,8 +182,7 @@ class SchemaModelGenerator:
# Create union of flat data models
enabled_memory_types = self.schemas
flat_model_union_types = tuple(
- self._flat_data_models[mt.memory_type]
- for mt in enabled_memory_types
+ self._flat_data_models[mt.memory_type] for mt in enabled_memory_types
)
if flat_model_union_types:
@@ -195,12 +191,15 @@ class SchemaModelGenerator:
# Fallback if no types are enabled
class GenericMemoryData(BaseModel):
"""Generic memory data (fallback)."""
+
memory_type: str = Field(..., description="Memory type identifier")
+
FlatDataUnion = GenericMemoryData # type: ignore
# Wrap the union in a BaseModel for JSON schema generation
class MemoryDataWrapper(BaseModel):
"""Wrapper model for memory data union."""
+
data: FlatDataUnion = Field(..., description="Memory data") # type: ignore
model_config = ConfigDict(extra="forbid")
@@ -245,7 +244,7 @@ class SchemaModelGenerator:
field_definitions["reasoning"] = (
str,
- Field('', description="reasoning"),
+ Field("", description="reasoning"),
)
for mt in enabled_memory_types:
@@ -262,15 +261,22 @@ class SchemaModelGenerator:
# List: List[FlatModel] = []
field_definitions[mt.memory_type] = (
List[flat_model], # type: ignore
- Field(default_factory=list, description=f"{mt.memory_type} memories (add or edit)"),
+ Field(
+ default_factory=list, description=f"{mt.memory_type} memories (add or edit)"
+ ),
)
# Use single generic model for overview edit (same for all memory types)
- generic_overview_edit = self.create_overview_edit_model(enabled_memory_types[0] if enabled_memory_types else None)
+ generic_overview_edit = self.create_overview_edit_model(
+ enabled_memory_types[0] if enabled_memory_types else None
+ )
field_definitions["edit_overview_uris"] = (
List[generic_overview_edit], # type: ignore
- Field(default_factory=list, description="Edit operations for .overview.md files using memory_type"),
+ Field(
+ default_factory=list,
+ description="Edit operations for .overview.md files using memory_type",
+ ),
)
field_definitions["delete_uris"] = (
@@ -280,8 +286,8 @@ class SchemaModelGenerator:
# Create model using create_model
StructuredMemoryOperations = create_model(
- 'StructuredMemoryOperations',
- __config__=ConfigDict(extra='ignore'),
+ "StructuredMemoryOperations",
+ __config__=ConfigDict(extra="ignore"),
__base__=FaultTolerantBaseModel,
**field_definitions,
)
@@ -298,10 +304,7 @@ class SchemaModelGenerator:
else:
# Single value (not None)
return False
- return (
- len(self.edit_overview_uris) == 0
- and len(self.delete_uris) == 0
- )
+ return len(self.edit_overview_uris) == 0 and len(self.delete_uris) == 0
def to_legacy_operations(self) -> Dict[str, Any]:
"""Convert new per-type structure to legacy write_uris/edit_uris format."""
@@ -314,12 +317,12 @@ class SchemaModelGenerator:
continue
if isinstance(value, list):
for item in value:
- if hasattr(item, 'uri') and item.uri:
+ if hasattr(item, "uri") and item.uri:
edit_uris.append(item)
else:
write_uris.append(item)
else:
- if hasattr(value, 'uri') and value.uri:
+ if hasattr(value, "uri") and value.uri:
edit_uris.append(value)
else:
write_uris.append(value)
@@ -405,7 +408,9 @@ class SchemaPromptGenerator:
if mt.fields:
lines.append("\n**Fields:**")
for field in mt.fields:
- lines.append(f"- `{field.name}` ({field.field_type.value}): {field.description}")
+ lines.append(
+ f"- `{field.name}` ({field.field_type.value}): {field.description}"
+ )
return "\n".join(lines)
diff --git a/openviking/session/memory/session_extract_context_provider.py b/openviking/session/memory/session_extract_context_provider.py
index d246690ec..4fa7a1fd2 100644
--- a/openviking/session/memory/session_extract_context_provider.py
+++ b/openviking/session/memory/session_extract_context_provider.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Session Extract Context Provider - 会话提取 Provider 实现
@@ -37,6 +37,7 @@ class SessionExtractContextProvider(ExtractContextProvider):
def _detect_language(self) -> str:
"""检测输出语言"""
from openviking.session.memory.utils import detect_language_from_conversation
+
conversation = self._assemble_conversation(self.messages)
config = get_openviking_config()
fallback_language = (config.language_fallback or "en").strip() or "en"
@@ -80,6 +81,7 @@ See GenericOverviewEdit in the JSON Schema below."""
def _build_conversation_message(self) -> Dict[str, Any]:
"""构建包含 Conversation History 的 user message"""
from datetime import datetime
+
if self.messages:
first_msg_time = getattr(self.messages[0], "created_at", None)
last_msg_time = getattr(self.messages[-1], "created_at", None)
@@ -111,7 +113,7 @@ Relative times (e.g., 'last week', 'next month') are based on Session Time, not
{conversation}
-After exploring, analyze the conversation and output ALL memory write/edit/delete operations in a single response. Do not output operations one at a time - gather all changes first, then return them together."""
+After exploring, analyze the conversation and output ALL memory write/edit/delete operations in a single response. Do not output operations one at a time - gather all changes first, then return them together.""",
}
def _assemble_conversation(self, messages: Any) -> str:
@@ -124,7 +126,6 @@ After exploring, analyze the conversation and output ALL memory write/edit/delet
Returns:
Formatted conversation string
"""
- import json
from openviking.message import Message
from openviking.message.part import ToolPart
@@ -158,7 +159,12 @@ After exploring, analyze the conversation and output ALL memory write/edit/delet
return "\n".join(all_lines) if all_lines else msg.content
conversation_sections.append(
- "\n".join([f"[{idx}][{msg.role}]: {format_message_with_parts(msg)}" for idx, msg in enumerate(messages)])
+ "\n".join(
+ [
+ f"[{idx}][{msg.role}]: {format_message_with_parts(msg)}"
+ for idx, msg in enumerate(messages)
+ ]
+ )
)
return "\n\n".join(section for section in conversation_sections if section)
@@ -209,7 +215,9 @@ After exploring, analyze the conversation and output ALL memory write/edit/delet
# Replace variables in directory path with actual user/agent space
user_space = ctx.user.user_space_name() if ctx and ctx.user else "default"
agent_space = ctx.user.agent_space_name() if ctx and ctx.user else "default"
- dir_path = schema.directory.replace("{user_space}", user_space).replace("{agent_space}", agent_space)
+ dir_path = schema.directory.replace("{user_space}", user_space).replace(
+ "{agent_space}", agent_space
+ )
# Always add .overview.md to read list
overview_files.add(f"{dir_path}/.overview.md")
@@ -240,9 +248,7 @@ After exploring, analyze the conversation and output ALL memory write/edit/delet
# 首先读取所有 .overview.md 文件(截断以避免窗口过大)
# 为 overview 读取创建一个基本的 tool_ctx
tool_ctx = ToolContext(
- request_ctx=ctx,
- transaction_handle=transaction_handle,
- default_search_uris=[]
+ request_ctx=ctx, transaction_handle=transaction_handle, default_search_uris=[]
)
for overview_uri in overview_files:
try:
@@ -250,11 +256,9 @@ After exploring, analyze the conversation and output ALL memory write/edit/delet
add_tool_call_pair_to_messages(
messages=pre_fetch_messages,
call_id=call_id_seq,
- tool_name='read',
- params={
- "uri": overview_uri
- },
- result=result_str
+ tool_name="read",
+ params={"uri": overview_uri},
+ result=result_str,
)
call_id_seq += 1
except Exception as e:
@@ -267,7 +271,7 @@ After exploring, analyze the conversation and output ALL memory write/edit/delet
tool_ctx_dir = ToolContext(
request_ctx=ctx,
transaction_handle=transaction_handle,
- default_search_uris=[dir_uri]
+ default_search_uris=[dir_uri],
)
try:
search_result = await search_tool.execute(
@@ -282,19 +286,18 @@ After exploring, analyze the conversation and output ALL memory write/edit/delet
if "error" in search_result:
result_value = f"Error: {search_result.get('error')}"
else:
- result_value = [m.get("uri", "") for m in search_result.get("memories", [])]
+ result_value = [
+ m.get("uri", "") for m in search_result.get("memories", [])
+ ]
else:
result_value = []
add_tool_call_pair_to_messages(
messages=pre_fetch_messages,
call_id=call_id_seq,
- tool_name='search',
- params={
- "query": "[Keywords]",
- "search_uri": dir_uri
- },
- result=result_value
+ tool_name="search",
+ params={"query": "[Keywords]", "search_uri": dir_uri},
+ result=result_value,
)
call_id_seq += 1
except Exception as e:
@@ -307,17 +310,14 @@ After exploring, analyze the conversation and output ALL memory write/edit/delet
add_tool_call_pair_to_messages(
messages=pre_fetch_messages,
call_id=call_id_seq,
- tool_name='read',
- params={
- "uri": file_uri
- },
- result=result_str
+ tool_name="read",
+ params={"uri": file_uri},
+ result=result_str,
)
call_id_seq += 1
except Exception as e:
logger.warning(f"Failed to read {file_uri}: {e}")
-
return pre_fetch_messages
def get_tools(self) -> List[str]:
@@ -351,4 +351,3 @@ After exploring, analyze the conversation and output ALL memory write/edit/delet
if os.path.exists(dir_path):
self._registry.load_from_directory(dir_path)
return self._registry
-
diff --git a/openviking/session/memory/tools.py b/openviking/session/memory/tools.py
index bfb31bc56..6818f0e12 100644
--- a/openviking/session/memory/tools.py
+++ b/openviking/session/memory/tools.py
@@ -1,16 +1,14 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Memory tools - encapsulate VikingFS read operations for ReAct loop.
Reference: bot/vikingbot/agent/tools/base.py design pattern
"""
-import json
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Tuple, Union
-from openviking.server.identity import RequestContext
from openviking.session.memory.utils import parse_memory_file_with_fields
from openviking.storage.viking_fs import VikingFS
from openviking_cli.utils import get_logger
@@ -18,17 +16,18 @@ from openviking_cli.utils import get_logger
logger = get_logger(__name__)
-
-
-
def optimize_search_result(result: Any, limit: int = 10) -> Any:
"""优化搜索结果以减少 Token 消耗,并过滤掉抽象文件。"""
if isinstance(result, dict) and "error" in result:
return {"error": extract_error_summary(result["error"])}
if isinstance(result, dict) and "memories" in result:
filtered = [
- item for item in result["memories"]
- if not (item.get("uri", "").endswith(".abstract.md") or item.get("uri", "").endswith(".overview.md"))
+ item
+ for item in result["memories"]
+ if not (
+ item.get("uri", "").endswith(".abstract.md")
+ or item.get("uri", "").endswith(".overview.md")
+ )
]
return [{"uri": item["uri"], "score": item["score"]} for item in filtered[:limit]]
return []
@@ -46,6 +45,7 @@ def optimize_tool_result(tool_name: str, result: Any) -> Any:
result["content"] = truncate_content(result["content"])
return result
+
def extract_error_summary(error: str) -> str:
if "File not found" in error:
return "File not found"
@@ -64,14 +64,9 @@ def add_tool_call_pair_to_messages(
result: Any,
) -> None:
"""Add a tool call pair with optimized format to save tokens."""
- messages.append({
- "role": "user",
- "content": {
- "tool_call_name": tool_name,
- "args": params,
- "result": result
- }
- })
+ messages.append(
+ {"role": "user", "content": {"tool_call_name": tool_name, "args": params, "result": result}}
+ )
def add_tool_call_items_to_messages(
diff --git a/openviking/session/memory/utils/__init__.py b/openviking/session/memory/utils/__init__.py
index 2ab288176..91524efe9 100644
--- a/openviking/session/memory/utils/__init__.py
+++ b/openviking/session/memory/utils/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Memory utilities package.
"""
@@ -11,6 +11,16 @@ from openviking.session.memory.utils.content import (
serialize_with_metadata,
truncate_content,
)
+from openviking.session.memory.utils.json_parser import (
+ _any_to_str,
+ _get_arg_type,
+ _get_origin_type,
+ extract_json_content,
+ parse_json_with_stability,
+ parse_value_with_tolerance,
+ remove_json_trailing_content,
+ value_fault_tolerance,
+)
from openviking.session.memory.utils.language import (
detect_language_from_conversation,
)
@@ -18,6 +28,10 @@ from openviking.session.memory.utils.messages import (
parse_memory_file_with_fields,
pretty_print_messages,
)
+from openviking.session.memory.utils.model import (
+ flat_model_to_dict,
+ model_to_dict,
+)
from openviking.session.memory.utils.uri import (
ResolvedOperation,
ResolvedOperations,
@@ -32,20 +46,6 @@ from openviking.session.memory.utils.uri import (
validate_operations_uris,
validate_uri_template,
)
-from openviking.session.memory.utils.json_parser import (
- _any_to_str,
- _get_arg_type,
- _get_origin_type,
- extract_json_content,
- parse_json_with_stability,
- parse_value_with_tolerance,
- remove_json_trailing_content,
- value_fault_tolerance,
-)
-from openviking.session.memory.utils.model import (
- model_to_dict,
- flat_model_to_dict,
-)
__all__ = [
# Content serialization
diff --git a/openviking/session/memory/utils/content.py b/openviking/session/memory/utils/content.py
index d66732aef..a39e8eebf 100644
--- a/openviking/session/memory/utils/content.py
+++ b/openviking/session/memory/utils/content.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Memory content serialization with metadata in HTML comments.
@@ -12,18 +12,11 @@ import re
from datetime import datetime
from typing import Any, Dict, Optional, Tuple
-
# Regex pattern to match the MEMORY_FIELDS HTML comment
-MEMORY_FIELDS_PATTERN = re.compile(
- r"\n\n<!--\s*MEMORY_FIELDS\s*\n(.*?)\n-->",
- re.DOTALL
-)
+MEMORY_FIELDS_PATTERN = re.compile(r"\n\n<!--\s*MEMORY_FIELDS\s*\n(.*?)\n-->", re.DOTALL)
# Alternative pattern that might appear at the end without leading newlines
-MEMORY_FIELDS_PATTERN_END = re.compile(
- r"<!--\s*MEMORY_FIELDS\s*\n(.*?)\n-->$",
- re.DOTALL
-)
+MEMORY_FIELDS_PATTERN_END = re.compile(r"<!--\s*MEMORY_FIELDS\s*\n(.*?)\n-->$", re.DOTALL)
def _serialize_datetime(obj: Any) -> Any:
@@ -75,10 +68,7 @@ def serialize_with_metadata(content: str, metadata: Dict[str, Any]) -> str:
# Serialize metadata to JSON with datetime handling
metadata_json = json.dumps(
- clean_metadata,
- indent=2,
- default=_serialize_datetime,
- ensure_ascii=False
+ clean_metadata, indent=2, default=_serialize_datetime, ensure_ascii=False
)
# Combine content and metadata
@@ -179,7 +169,7 @@ def truncate_content(content: str, max_chars: int = DEFAULT_TRUNCATE_MAX_CHARS)
# 从 max_chars 位置向前找最近的换行符,保持完整行
truncated = content[:max_chars]
- last_newline = truncated.rfind('\n')
+ last_newline = truncated.rfind("\n")
if last_newline > 0:
truncated = truncated[:last_newline]
diff --git a/openviking/session/memory/utils/json_parser.py b/openviking/session/memory/utils/json_parser.py
index 6b1474c8d..71de8b222 100644
--- a/openviking/session/memory/utils/json_parser.py
+++ b/openviking/session/memory/utils/json_parser.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
JSON stable parsing - Five-Layer Fault Tolerance Architecture.
@@ -12,7 +12,17 @@ Layer 5: Validation Tolerance - TypeAdapter(strict=False) + list item filtering
import json
from types import UnionType
-from typing import Any, Dict, List, Optional, Tuple, Type, get_type_hints, get_origin, get_args, Union
+from typing import (
+ Any,
+ List,
+ Optional,
+ Tuple,
+ Type,
+ Union,
+ get_args,
+ get_origin,
+ get_type_hints,
+)
import json_repair
from pydantic import TypeAdapter
@@ -58,8 +68,8 @@ def extract_json_content(s: str) -> str:
temp_s = s
# Find first { or [
- first_brace = temp_s.find('{')
- first_bracket = temp_s.find('[')
+ first_brace = temp_s.find("{")
+ first_bracket = temp_s.find("[")
start_idx = 0
if first_brace != -1 and first_bracket != -1:
@@ -76,8 +86,8 @@ def extract_json_content(s: str) -> str:
temp_s = temp_s[start_idx:]
# Find last } or ]
- last_brace = temp_s.rfind('}')
- last_bracket = temp_s.rfind(']')
+ last_brace = temp_s.rfind("}")
+ last_bracket = temp_s.rfind("]")
end_idx = len(temp_s)
if last_brace != -1 and last_bracket != -1:
@@ -180,7 +190,7 @@ def _any_to_str(value) -> str:
elif isinstance(value, dict):
return json.dumps(value, ensure_ascii=False)
elif isinstance(value, (int, bool, float)):
- return f'{value}'
+ return f"{value}"
return str(value)
@@ -206,7 +216,7 @@ def value_fault_tolerance(field_type, value):
origin_type = _get_origin_type(field_type)
# Handle json_repair converting None to 'None'
- if value == 'None':
+ if value == "None":
if origin_type is not str:
return None
@@ -215,7 +225,7 @@ def value_fault_tolerance(field_type, value):
return _any_to_str(value)
elif origin_type is int:
if isinstance(value, str):
- if value is None or value == 'None':
+ if value is None or value == "None":
return 0
try:
return int(value)
@@ -223,7 +233,7 @@ def value_fault_tolerance(field_type, value):
pass
elif origin_type is float:
if isinstance(value, str):
- if value is None or value == 'None':
+ if value is None or value == "None":
return 0.0
try:
return float(value)
@@ -263,9 +273,13 @@ def parse_value_with_tolerance(value, annotation):
if isinstance(value, str):
return value
else:
- return json.dumps(value, ensure_ascii=False) if isinstance(value, (dict, list)) else str(value)
+ return (
+ json.dumps(value, ensure_ascii=False)
+ if isinstance(value, (dict, list))
+ else str(value)
+ )
- if value == 'None':
+ if value == "None":
return None
# Apply value fault tolerance (inline for efficiency)
@@ -274,7 +288,7 @@ def parse_value_with_tolerance(value, annotation):
parsed_value = _any_to_str(value)
elif origin_type is int:
if isinstance(value, str):
- if value == 'None':
+ if value == "None":
parsed_value = 0
else:
try:
@@ -285,7 +299,7 @@ def parse_value_with_tolerance(value, annotation):
parsed_value = value
elif origin_type is float:
if isinstance(value, str):
- if value == 'None':
+ if value == "None":
parsed_value = 0.0
else:
try:
@@ -308,11 +322,10 @@ def parse_value_with_tolerance(value, annotation):
try:
return TypeAdapter(annotation).validate_python(parsed_value, strict=False)
except Exception as e:
- logger.warning(f'TypeAdapter validation failed: {e}')
+ logger.warning(f"TypeAdapter validation failed: {e}")
# For list types, try filtering invalid items
- if (get_origin(annotation) is list and
- isinstance(parsed_value, list)):
+ if get_origin(annotation) is list and isinstance(parsed_value, list):
filtered_items = []
item_type = _get_arg_type(annotation)
if item_type is not None:
@@ -416,8 +429,7 @@ def parse_json_with_stability(
if field_name in field_types:
try:
tolerant_data[field_name] = parse_value_with_tolerance(
- field_value,
- field_types[field_name]
+ field_value, field_types[field_name]
)
except Exception as field_e:
logger.warning(f"Field {field_name} parsing failed: {field_e}")
@@ -428,5 +440,3 @@ def parse_json_with_stability(
return model_class.model_validate(tolerant_data), None
except Exception as e2:
return None, f"Model validation failed even after tolerance: {e} (fallback: {e2})"
-
-
diff --git a/openviking/session/memory/utils/language.py b/openviking/session/memory/utils/language.py
index b87f855e7..8fcd8713f 100644
--- a/openviking/session/memory/utils/language.py
+++ b/openviking/session/memory/utils/language.py
@@ -1,11 +1,10 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Language detection utilities.
"""
import re
-from typing import Optional
from openviking_cli.utils import get_logger
diff --git a/openviking/session/memory/utils/messages.py b/openviking/session/memory/utils/messages.py
index 9c3de6972..289c944a9 100644
--- a/openviking/session/memory/utils/messages.py
+++ b/openviking/session/memory/utils/messages.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Message formatting and memory file parsing utilities.
"""
diff --git a/openviking/session/memory/utils/model.py b/openviking/session/memory/utils/model.py
index e0134cc3b..a3a9132df 100644
--- a/openviking/session/memory/utils/model.py
+++ b/openviking/session/memory/utils/model.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Model utilities - shared model conversion functions.
"""
@@ -17,11 +17,11 @@ def model_to_dict(model: Any, exclude_none: bool = True) -> Dict[str, Any]:
Returns:
Dictionary representation of the model
"""
- if hasattr(model, 'model_dump'):
+ if hasattr(model, "model_dump"):
if exclude_none:
return model.model_dump(exclude_none=True)
return model.model_dump()
- elif hasattr(model, 'dict'):
+ elif hasattr(model, "dict"):
# For backward compatibility with older Pydantic
if exclude_none:
return model.dict(exclude_none=True)
diff --git a/openviking/session/memory/utils/uri.py b/openviking/session/memory/utils/uri.py
index 0ce9f64fb..081ddb007 100644
--- a/openviking/session/memory/utils/uri.py
+++ b/openviking/session/memory/utils/uri.py
@@ -1,12 +1,12 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
URI generation and validation utilities.
"""
import re
from dataclasses import dataclass
-from typing import Any, Dict, List, Optional, Set, Tuple, Type
+from typing import Any, Dict, List, Optional, Set, Tuple
from openviking.session.memory.dataclass import MemoryTypeSchema
from openviking.session.memory.memory_type_registry import MemoryTypeRegistry
@@ -18,6 +18,7 @@ logger = get_logger(__name__)
@dataclass
class ResolvedOperation:
"""A resolved memory operation with URI and memory_type."""
+
model: Any # The flat model data
uri: str # The resolved URI
memory_type: str # The memory type (e.g., 'tools', 'skills', 'events')
@@ -130,7 +131,9 @@ def collect_allowed_directories(
allowed_dirs = set()
for schema in schemas:
if schema.directory:
- dir_path = schema.directory.replace("{user_space}", user_space).replace("{agent_space}", agent_space)
+ dir_path = schema.directory.replace("{user_space}", user_space).replace(
+ "{agent_space}", agent_space
+ )
allowed_dirs.add(dir_path)
return allowed_dirs
@@ -163,7 +166,9 @@ def collect_allowed_path_patterns(
pattern_parts.append(schema.filename_template)
if pattern_parts:
pattern = "/".join(pattern_parts)
- pattern = pattern.replace("{user_space}", user_space).replace("{agent_space}", agent_space)
+ pattern = pattern.replace("{user_space}", user_space).replace(
+ "{agent_space}", agent_space
+ )
allowed_patterns.add(pattern)
return allowed_patterns
@@ -304,10 +309,10 @@ def resolve_flat_model_uri(
# Get memory_type from parameter or from model
if memory_type:
memory_type_str = memory_type
- elif hasattr(flat_model, 'memory_type'):
+ elif hasattr(flat_model, "memory_type"):
memory_type_str = flat_model.memory_type
- elif isinstance(flat_model, dict) and 'memory_type' in flat_model:
- memory_type_str = flat_model['memory_type']
+ elif isinstance(flat_model, dict) and "memory_type" in flat_model:
+ memory_type_str = flat_model["memory_type"]
else:
raise ValueError("Flat model missing 'memory_type' field")
@@ -316,10 +321,10 @@ def resolve_flat_model_uri(
raise ValueError(f"Unknown memory type: {memory_type_str}")
# Check if model already has a uri field
- if hasattr(flat_model, 'uri') and flat_model.uri is not None:
+ if hasattr(flat_model, "uri") and flat_model.uri is not None:
return flat_model.uri
- elif isinstance(flat_model, dict) and 'uri' in flat_model and flat_model['uri'] is not None:
- return flat_model['uri']
+ elif isinstance(flat_model, dict) and "uri" in flat_model and flat_model["uri"] is not None:
+ return flat_model["uri"]
# Extract URI fields and generate URI
uri_fields = extract_uri_fields_from_flat_model(flat_model, schema)
@@ -348,10 +353,10 @@ def resolve_overview_edit_uri(
ValueError: If memory_type not found or directory not found
"""
# Get memory_type from model
- if hasattr(overview_model, 'memory_type'):
+ if hasattr(overview_model, "memory_type"):
memory_type_str = overview_model.memory_type
elif isinstance(overview_model, dict):
- memory_type_str = overview_model.get('memory_type')
+ memory_type_str = overview_model.get("memory_type")
else:
raise ValueError("overview_model must have memory_type field")
@@ -364,7 +369,9 @@ def resolve_overview_edit_uri(
raise ValueError(f"Memory type {memory_type_str} has no directory configured")
# Substitute user_space and agent_space in directory
- directory = schema.directory.replace("{user_space}", user_space).replace("{agent_space}", agent_space)
+ directory = schema.directory.replace("{user_space}", user_space).replace(
+ "{agent_space}", agent_space
+ )
# Return the .overview.md URI
return f"{directory}/.overview.md"
@@ -376,7 +383,9 @@ class ResolvedOperations:
def __init__(self):
self.write_operations: List[ResolvedOperation] = []
self.edit_operations: List[ResolvedOperation] = []
- self.edit_overview_operations: List[Tuple[Any, str]] = [] # (overview_edit_model, overview_uri)
+ self.edit_overview_operations: List[
+ Tuple[Any, str]
+ ] = [] # (overview_edit_model, overview_uri)
self.delete_operations: List[Tuple[str, str]] = [] # (uri_str, uri_str) - just the uri
self.errors: List[str] = []
@@ -407,7 +416,7 @@ def resolve_all_operations(
resolved = ResolvedOperations()
# Check if using new per-memory_type format
- memory_type_fields = getattr(operations, '_memory_type_fields', None)
+ memory_type_fields = getattr(operations, "_memory_type_fields", None)
if memory_type_fields:
# New format: iterate each memory_type field
for field_name in memory_type_fields:
@@ -418,44 +427,54 @@ def resolve_all_operations(
for item in items:
# Determine if edit (has uri) or write
is_edit = False
- if hasattr(item, 'uri') and item.uri:
+ if hasattr(item, "uri") and item.uri:
is_edit = True
- elif isinstance(item, dict) and item.get('uri'):
+ elif isinstance(item, dict) and item.get("uri"):
is_edit = True
# Convert to dict for URI resolution
- item_dict = dict(item) if hasattr(item, 'model_dump') else dict(item)
+ item_dict = dict(item) if hasattr(item, "model_dump") else dict(item)
try:
- uri = resolve_flat_model_uri(item_dict, registry, user_space, agent_space, memory_type=field_name)
+ uri = resolve_flat_model_uri(
+ item_dict, registry, user_space, agent_space, memory_type=field_name
+ )
if is_edit:
- resolved.edit_operations.append(ResolvedOperation(model=item_dict, uri=uri, memory_type=field_name))
+ resolved.edit_operations.append(
+ ResolvedOperation(model=item_dict, uri=uri, memory_type=field_name)
+ )
else:
- resolved.write_operations.append(ResolvedOperation(model=item_dict, uri=uri, memory_type=field_name))
+ resolved.write_operations.append(
+ ResolvedOperation(model=item_dict, uri=uri, memory_type=field_name)
+ )
except Exception as e:
resolved.errors.append(f"Failed to resolve {field_name} operation: {e}")
else:
# Legacy format
- write_uris = operations.write_uris if hasattr(operations, 'write_uris') else []
- edit_uris = operations.edit_uris if hasattr(operations, 'edit_uris') else []
+ write_uris = operations.write_uris if hasattr(operations, "write_uris") else []
+ edit_uris = operations.edit_uris if hasattr(operations, "edit_uris") else []
for op in write_uris:
try:
uri = resolve_flat_model_uri(op, registry, user_space, agent_space)
# Legacy format: try to get memory_type from model, otherwise empty
- memory_type = op.get('memory_type', '') if isinstance(op, dict) else ''
- resolved.write_operations.append(ResolvedOperation(model=op, uri=uri, memory_type=memory_type))
+ memory_type = op.get("memory_type", "") if isinstance(op, dict) else ""
+ resolved.write_operations.append(
+ ResolvedOperation(model=op, uri=uri, memory_type=memory_type)
+ )
except Exception as e:
resolved.errors.append(f"Failed to resolve write operation: {e}")
for op in edit_uris:
try:
uri = resolve_flat_model_uri(op, registry, user_space, agent_space)
- memory_type = op.get('memory_type', '') if isinstance(op, dict) else ''
- resolved.edit_operations.append(ResolvedOperation(model=op, uri=uri, memory_type=memory_type))
+ memory_type = op.get("memory_type", "") if isinstance(op, dict) else ""
+ resolved.edit_operations.append(
+ ResolvedOperation(model=op, uri=uri, memory_type=memory_type)
+ )
except Exception as e:
resolved.errors.append(f"Failed to resolve edit operation: {e}")
# Resolve edit_overview operations (overview edit models)
- if hasattr(operations, 'edit_overview_uris'):
+ if hasattr(operations, "edit_overview_uris"):
for op in operations.edit_overview_uris:
try:
uri = resolve_overview_edit_uri(op, registry, user_space, agent_space)
@@ -464,7 +483,7 @@ def resolve_all_operations(
resolved.errors.append(f"Failed to resolve edit_overview operation: {e}")
# Resolve delete operations (already URI strings)
- if hasattr(operations, 'delete_uris'):
+ if hasattr(operations, "delete_uris"):
for uri in operations.delete_uris:
try:
# Delete operations are already URIs, just pass them through
diff --git a/openviking/session/memory_archiver.py b/openviking/session/memory_archiver.py
index 680ae4028..9f610c2bc 100644
--- a/openviking/session/memory_archiver.py
+++ b/openviking/session/memory_archiver.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Cold-storage archival for stale memories based on hotness scoring.
Moves memories with low hotness scores to an archive directory,
diff --git a/openviking/session/memory_deduplicator.py b/openviking/session/memory_deduplicator.py
index f0ccd74ee..1459292ee 100644
--- a/openviking/session/memory_deduplicator.py
+++ b/openviking/session/memory_deduplicator.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Memory Deduplicator for OpenViking.
diff --git a/openviking/session/memory_extractor.py b/openviking/session/memory_extractor.py
index 9a2406997..820111638 100644
--- a/openviking/session/memory_extractor.py
+++ b/openviking/session/memory_extractor.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Memory Extractor for OpenViking.
diff --git a/openviking/session/session.py b/openviking/session/session.py
index a71bf535b..3845b9d04 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Session management for OpenViking.
Session as Context: Sessions integrated into L0/L1/L2 system.
diff --git a/openviking/session/tool_skill_utils.py b/openviking/session/tool_skill_utils.py
index c007e06e8..bdaab66e0 100644
--- a/openviking/session/tool_skill_utils.py
+++ b/openviking/session/tool_skill_utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from __future__ import annotations
diff --git a/openviking/storage/__init__.py b/openviking/storage/__init__.py
index 752fc3d88..04e340dd9 100644
--- a/openviking/storage/__init__.py
+++ b/openviking/storage/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Storage layer interfaces and implementations."""
from openviking.storage.errors import (
diff --git a/openviking/storage/collection_schemas.py b/openviking/storage/collection_schemas.py
index d41918b70..9fdb6fa72 100644
--- a/openviking/storage/collection_schemas.py
+++ b/openviking/storage/collection_schemas.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Collection schema definitions for OpenViking.
diff --git a/openviking/storage/errors.py b/openviking/storage/errors.py
index def786be8..84840fd27 100644
--- a/openviking/storage/errors.py
+++ b/openviking/storage/errors.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Storage-layer exceptions."""
diff --git a/openviking/storage/expr.py b/openviking/storage/expr.py
index ef3aa8591..da3115bec 100644
--- a/openviking/storage/expr.py
+++ b/openviking/storage/expr.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Filter expression AST for vector store queries."""
from __future__ import annotations
diff --git a/openviking/storage/local_fs.py b/openviking/storage/local_fs.py
index 3d23566dc..a42810e1f 100644
--- a/openviking/storage/local_fs.py
+++ b/openviking/storage/local_fs.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import json
import os
import re
diff --git a/openviking/storage/observers/__init__.py b/openviking/storage/observers/__init__.py
index aa2d02185..cc657ddd9 100644
--- a/openviking/storage/observers/__init__.py
+++ b/openviking/storage/observers/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from .base_observer import BaseObserver
from .lock_observer import LockObserver
from .prometheus_observer import (
diff --git a/openviking/storage/observers/base_observer.py b/openviking/storage/observers/base_observer.py
index b0cd25e66..57a06c014 100644
--- a/openviking/storage/observers/base_observer.py
+++ b/openviking/storage/observers/base_observer.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
BaseObserver: Abstract base class for storage system observers.
diff --git a/openviking/storage/observers/lock_observer.py b/openviking/storage/observers/lock_observer.py
index 92521790f..4ae838f18 100644
--- a/openviking/storage/observers/lock_observer.py
+++ b/openviking/storage/observers/lock_observer.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""LockObserver: Lock system observability."""
import time
diff --git a/openviking/storage/observers/prometheus_observer.py b/openviking/storage/observers/prometheus_observer.py
index f3be59273..35f33e40c 100644
--- a/openviking/storage/observers/prometheus_observer.py
+++ b/openviking/storage/observers/prometheus_observer.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""PrometheusObserver: Prometheus metrics exporter for OpenViking."""
import threading
diff --git a/openviking/storage/observers/queue_observer.py b/openviking/storage/observers/queue_observer.py
index 4d544f9ee..0afd840f8 100644
--- a/openviking/storage/observers/queue_observer.py
+++ b/openviking/storage/observers/queue_observer.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
QueueObserver: Queue system observability tool.
diff --git a/openviking/storage/observers/retrieval_observer.py b/openviking/storage/observers/retrieval_observer.py
index a3a79a74c..6505a5650 100644
--- a/openviking/storage/observers/retrieval_observer.py
+++ b/openviking/storage/observers/retrieval_observer.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
RetrievalObserver: Retrieval system observability tool.
diff --git a/openviking/storage/observers/vikingdb_observer.py b/openviking/storage/observers/vikingdb_observer.py
index aac577c42..a6c836c36 100644
--- a/openviking/storage/observers/vikingdb_observer.py
+++ b/openviking/storage/observers/vikingdb_observer.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
VikingDBObserver: VikingDB storage observability tool.
diff --git a/openviking/storage/observers/vlm_observer.py b/openviking/storage/observers/vlm_observer.py
index 8957caec9..20af3273f 100644
--- a/openviking/storage/observers/vlm_observer.py
+++ b/openviking/storage/observers/vlm_observer.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
VLMObserver: VLM system observability tool.
diff --git a/openviking/storage/queuefs/__init__.py b/openviking/storage/queuefs/__init__.py
index 87514a830..f98e0b93c 100644
--- a/openviking/storage/queuefs/__init__.py
+++ b/openviking/storage/queuefs/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from .embedding_msg import EmbeddingMsg
from .embedding_queue import EmbeddingQueue
from .embedding_tracker import EmbeddingTaskTracker
diff --git a/openviking/storage/queuefs/embedding_msg.py b/openviking/storage/queuefs/embedding_msg.py
index af0e95eea..9a5917dbf 100644
--- a/openviking/storage/queuefs/embedding_msg.py
+++ b/openviking/storage/queuefs/embedding_msg.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import json
from dataclasses import asdict, dataclass
from typing import Any, Dict, List, Optional, Union
diff --git a/openviking/storage/queuefs/embedding_msg_converter.py b/openviking/storage/queuefs/embedding_msg_converter.py
index 133d0de6b..cef13360c 100644
--- a/openviking/storage/queuefs/embedding_msg_converter.py
+++ b/openviking/storage/queuefs/embedding_msg_converter.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Embedding Message Converter.
diff --git a/openviking/storage/queuefs/embedding_queue.py b/openviking/storage/queuefs/embedding_queue.py
index 5fb1f4af4..7f2af0ba0 100644
--- a/openviking/storage/queuefs/embedding_queue.py
+++ b/openviking/storage/queuefs/embedding_queue.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from typing import Optional
from openviking_cli.utils.logger import get_logger
diff --git a/openviking/storage/queuefs/embedding_tracker.py b/openviking/storage/queuefs/embedding_tracker.py
index 60dc85f76..2da33ecec 100644
--- a/openviking/storage/queuefs/embedding_tracker.py
+++ b/openviking/storage/queuefs/embedding_tracker.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Embedding Task Tracker for tracking embedding task completion status."""
import asyncio
diff --git a/openviking/storage/queuefs/named_queue.py b/openviking/storage/queuefs/named_queue.py
index ce7705b79..8a7fd4f40 100644
--- a/openviking/storage/queuefs/named_queue.py
+++ b/openviking/storage/queuefs/named_queue.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import abc
import json
import threading
diff --git a/openviking/storage/queuefs/queue_manager.py b/openviking/storage/queuefs/queue_manager.py
index 54713e8f0..76c14c3c2 100644
--- a/openviking/storage/queuefs/queue_manager.py
+++ b/openviking/storage/queuefs/queue_manager.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
QueueManager: Encapsulates AGFS QueueFS plugin operations.
All queues are managed through NamedQueue.
@@ -150,7 +150,11 @@ class QueueManager:
if thread.is_alive():
return
- max_concurrent = self._max_concurrent_embedding if queue.name == self.EMBEDDING else self._max_concurrent_semantic
+ max_concurrent = (
+ self._max_concurrent_embedding
+ if queue.name == self.EMBEDDING
+ else self._max_concurrent_semantic
+ )
stop_event = threading.Event()
self._queue_stop_events[queue.name] = stop_event
thread = threading.Thread(
diff --git a/openviking/storage/queuefs/semantic_dag.py b/openviking/storage/queuefs/semantic_dag.py
index 55cacc691..3eac0905f 100644
--- a/openviking/storage/queuefs/semantic_dag.py
+++ b/openviking/storage/queuefs/semantic_dag.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Semantic DAG executor with event-driven lazy dispatch."""
import asyncio
diff --git a/openviking/storage/queuefs/semantic_msg.py b/openviking/storage/queuefs/semantic_msg.py
index fbd56647e..ba27d841a 100644
--- a/openviking/storage/queuefs/semantic_msg.py
+++ b/openviking/storage/queuefs/semantic_msg.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""SemanticMsg: Semantic extraction queue message dataclass."""
import json
diff --git a/openviking/storage/queuefs/semantic_processor.py b/openviking/storage/queuefs/semantic_processor.py
index dd5e284cf..1ff264d73 100644
--- a/openviking/storage/queuefs/semantic_processor.py
+++ b/openviking/storage/queuefs/semantic_processor.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""SemanticProcessor: Processes messages from SemanticQueue, generates .abstract.md and .overview.md."""
import asyncio
diff --git a/openviking/storage/queuefs/semantic_queue.py b/openviking/storage/queuefs/semantic_queue.py
index 4f412d9cc..8f0be6f95 100644
--- a/openviking/storage/queuefs/semantic_queue.py
+++ b/openviking/storage/queuefs/semantic_queue.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""SemanticQueue: Semantic extraction queue."""
from typing import Optional
diff --git a/openviking/storage/stats_aggregator.py b/openviking/storage/stats_aggregator.py
index 76bf62403..da320e6a4 100644
--- a/openviking/storage/stats_aggregator.py
+++ b/openviking/storage/stats_aggregator.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Memory health statistics aggregator.
Queries VikingDB indexes and the hotness_score function to produce
diff --git a/openviking/storage/transaction/__init__.py b/openviking/storage/transaction/__init__.py
index 52e77ff72..9b8739468 100644
--- a/openviking/storage/transaction/__init__.py
+++ b/openviking/storage/transaction/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Transaction module for OpenViking.
diff --git a/openviking/storage/transaction/lock_context.py b/openviking/storage/transaction/lock_context.py
index 4d1d8443d..e60525d09 100644
--- a/openviking/storage/transaction/lock_context.py
+++ b/openviking/storage/transaction/lock_context.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""LockContext — async context manager for acquiring/releasing path locks."""
from typing import Optional
diff --git a/openviking/storage/transaction/lock_handle.py b/openviking/storage/transaction/lock_handle.py
index 7b5be5d9a..8ab32a116 100644
--- a/openviking/storage/transaction/lock_handle.py
+++ b/openviking/storage/transaction/lock_handle.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Lock handle and LockOwner protocol for PathLock integration."""
import time
diff --git a/openviking/storage/transaction/lock_manager.py b/openviking/storage/transaction/lock_manager.py
index 0b46d3252..5748ef69d 100644
--- a/openviking/storage/transaction/lock_manager.py
+++ b/openviking/storage/transaction/lock_manager.py
@@ -1,11 +1,11 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""LockManager — global singleton managing lock lifecycle and redo recovery."""
import asyncio
import json
import time
-from typing import Any, Dict, Optional, List
+from typing import Any, Dict, List, Optional
from openviking.pyagfs import AGFSClient
from openviking.storage.transaction.lock_handle import LockHandle
diff --git a/openviking/storage/transaction/redo_log.py b/openviking/storage/transaction/redo_log.py
index 80d07dff2..467d246bd 100644
--- a/openviking/storage/transaction/redo_log.py
+++ b/openviking/storage/transaction/redo_log.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Lightweight redo log for crash recovery of session_memory operations."""
import json
diff --git a/openviking/storage/vectordb/__init__.py b/openviking/storage/vectordb/__init__.py
index 34a1a0f9f..643367a69 100644
--- a/openviking/storage/vectordb/__init__.py
+++ b/openviking/storage/vectordb/__init__.py
@@ -1,3 +1,3 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""VectorDB storage backend."""
diff --git a/openviking/storage/vectordb/collection/__init__.py b/openviking/storage/vectordb/collection/__init__.py
index 94bee3e36..88bb52e7c 100644
--- a/openviking/storage/vectordb/collection/__init__.py
+++ b/openviking/storage/vectordb/collection/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Collection implementations for VikingDB."""
from openviking.storage.vectordb.collection.collection import Collection, ICollection
diff --git a/openviking/storage/vectordb/collection/collection.py b/openviking/storage/vectordb/collection/collection.py
index 97d259fdf..4d50cdafe 100644
--- a/openviking/storage/vectordb/collection/collection.py
+++ b/openviking/storage/vectordb/collection/collection.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import importlib
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Type
diff --git a/openviking/storage/vectordb/collection/http_collection.py b/openviking/storage/vectordb/collection/http_collection.py
index 1b780f36e..530a7af6c 100644
--- a/openviking/storage/vectordb/collection/http_collection.py
+++ b/openviking/storage/vectordb/collection/http_collection.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import copy
import json
from typing import Any, Dict, List, Optional
diff --git a/openviking/storage/vectordb/collection/local_collection.py b/openviking/storage/vectordb/collection/local_collection.py
index dc84d39f1..278e21637 100644
--- a/openviking/storage/vectordb/collection/local_collection.py
+++ b/openviking/storage/vectordb/collection/local_collection.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import datetime
import json
import os
diff --git a/openviking/storage/vectordb/collection/result.py b/openviking/storage/vectordb/collection/result.py
index d094ca1ca..d796c70d0 100644
--- a/openviking/storage/vectordb/collection/result.py
+++ b/openviking/storage/vectordb/collection/result.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
diff --git a/openviking/storage/vectordb/collection/vikingdb_clients.py b/openviking/storage/vectordb/collection/vikingdb_clients.py
index 192bad22e..4f1d25520 100644
--- a/openviking/storage/vectordb/collection/vikingdb_clients.py
+++ b/openviking/storage/vectordb/collection/vikingdb_clients.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import json
from typing import Any, Dict, Optional
diff --git a/openviking/storage/vectordb/collection/vikingdb_collection.py b/openviking/storage/vectordb/collection/vikingdb_collection.py
index b9995a1f5..94577e27c 100644
--- a/openviking/storage/vectordb/collection/vikingdb_collection.py
+++ b/openviking/storage/vectordb/collection/vikingdb_collection.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import json
from typing import Any, Dict, List, Optional
diff --git a/openviking/storage/vectordb/collection/volcengine_clients.py b/openviking/storage/vectordb/collection/volcengine_clients.py
index 4f2798b80..9eac48460 100644
--- a/openviking/storage/vectordb/collection/volcengine_clients.py
+++ b/openviking/storage/vectordb/collection/volcengine_clients.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import json
import requests # type: ignore
diff --git a/openviking/storage/vectordb/collection/volcengine_collection.py b/openviking/storage/vectordb/collection/volcengine_collection.py
index 30845b15d..855eff889 100644
--- a/openviking/storage/vectordb/collection/volcengine_collection.py
+++ b/openviking/storage/vectordb/collection/volcengine_collection.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import copy
import json
from typing import Any, Dict, List, Optional
diff --git a/openviking/storage/vectordb/engine/__init__.py b/openviking/storage/vectordb/engine/__init__.py
index 843103e92..564015652 100644
--- a/openviking/storage/vectordb/engine/__init__.py
+++ b/openviking/storage/vectordb/engine/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Stable runtime loader for vectordb native engine variants."""
from __future__ import annotations
diff --git a/openviking/storage/vectordb/engine/_python_api.py b/openviking/storage/vectordb/engine/_python_api.py
index c82d0ea76..549aec11d 100644
--- a/openviking/storage/vectordb/engine/_python_api.py
+++ b/openviking/storage/vectordb/engine/_python_api.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from __future__ import annotations
import struct
diff --git a/openviking/storage/vectordb/index/__init__.py b/openviking/storage/vectordb/index/__init__.py
index 819b3465d..236633478 100644
--- a/openviking/storage/vectordb/index/__init__.py
+++ b/openviking/storage/vectordb/index/__init__.py
@@ -1,2 +1,2 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
diff --git a/openviking/storage/vectordb/index/index.py b/openviking/storage/vectordb/index/index.py
index 81b6b1b85..0e3bae0ab 100644
--- a/openviking/storage/vectordb/index/index.py
+++ b/openviking/storage/vectordb/index/index.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Tuple, Union
diff --git a/openviking/storage/vectordb/index/local_index.py b/openviking/storage/vectordb/index/local_index.py
index eadd17c5e..35f0940dc 100644
--- a/openviking/storage/vectordb/index/local_index.py
+++ b/openviking/storage/vectordb/index/local_index.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import json
import math
import os
diff --git a/openviking/storage/vectordb/meta/__init__.py b/openviking/storage/vectordb/meta/__init__.py
index 819b3465d..236633478 100644
--- a/openviking/storage/vectordb/meta/__init__.py
+++ b/openviking/storage/vectordb/meta/__init__.py
@@ -1,2 +1,2 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
diff --git a/openviking/storage/vectordb/meta/collection_meta.py b/openviking/storage/vectordb/meta/collection_meta.py
index 59a5ceb51..191127161 100644
--- a/openviking/storage/vectordb/meta/collection_meta.py
+++ b/openviking/storage/vectordb/meta/collection_meta.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import copy
from typing import Any, Dict, Optional
diff --git a/openviking/storage/vectordb/meta/dict.py b/openviking/storage/vectordb/meta/dict.py
index b775ea5da..b155941bf 100644
--- a/openviking/storage/vectordb/meta/dict.py
+++ b/openviking/storage/vectordb/meta/dict.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from abc import ABC, abstractmethod
from typing import Any
from typing import Dict as TypeDict
diff --git a/openviking/storage/vectordb/meta/index_meta.py b/openviking/storage/vectordb/meta/index_meta.py
index 9e3762e13..4bea13057 100644
--- a/openviking/storage/vectordb/meta/index_meta.py
+++ b/openviking/storage/vectordb/meta/index_meta.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import copy
from typing import Any, Dict, List, Optional
diff --git a/openviking/storage/vectordb/meta/local_dict.py b/openviking/storage/vectordb/meta/local_dict.py
index 1fad3167c..b4b8e6f47 100644
--- a/openviking/storage/vectordb/meta/local_dict.py
+++ b/openviking/storage/vectordb/meta/local_dict.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import copy
import json
from typing import Any, Dict, Optional
diff --git a/openviking/storage/vectordb/project/__init__.py b/openviking/storage/vectordb/project/__init__.py
index 819b3465d..236633478 100644
--- a/openviking/storage/vectordb/project/__init__.py
+++ b/openviking/storage/vectordb/project/__init__.py
@@ -1,2 +1,2 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
diff --git a/openviking/storage/vectordb/project/http_project.py b/openviking/storage/vectordb/project/http_project.py
index b439661e6..703e59a3f 100644
--- a/openviking/storage/vectordb/project/http_project.py
+++ b/openviking/storage/vectordb/project/http_project.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from typing import Any, Dict, Optional
from openviking.storage.vectordb.collection.collection import Collection
diff --git a/openviking/storage/vectordb/project/local_project.py b/openviking/storage/vectordb/project/local_project.py
index 035a10094..d2adde60c 100644
--- a/openviking/storage/vectordb/project/local_project.py
+++ b/openviking/storage/vectordb/project/local_project.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import json
import os
from typing import Any, Dict, Optional
diff --git a/openviking/storage/vectordb/project/project.py b/openviking/storage/vectordb/project/project.py
index 1ed5d13c0..edebadbb0 100644
--- a/openviking/storage/vectordb/project/project.py
+++ b/openviking/storage/vectordb/project/project.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from abc import ABC, abstractmethod
from typing import Any, Dict
diff --git a/openviking/storage/vectordb/project/project_group.py b/openviking/storage/vectordb/project/project_group.py
index 847b314fa..88a0cdc6c 100644
--- a/openviking/storage/vectordb/project/project_group.py
+++ b/openviking/storage/vectordb/project/project_group.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import os
from typing import Dict, Optional
diff --git a/openviking/storage/vectordb/project/vikingdb_project.py b/openviking/storage/vectordb/project/vikingdb_project.py
index 3f3d3bfd5..18be7f106 100644
--- a/openviking/storage/vectordb/project/vikingdb_project.py
+++ b/openviking/storage/vectordb/project/vikingdb_project.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from typing import Any, Dict, List, Optional
from openviking.storage.vectordb.collection.collection import (
diff --git a/openviking/storage/vectordb/project/volcengine_project.py b/openviking/storage/vectordb/project/volcengine_project.py
index 25ccf8b22..8c7e74860 100644
--- a/openviking/storage/vectordb/project/volcengine_project.py
+++ b/openviking/storage/vectordb/project/volcengine_project.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from typing import Any, Dict, Optional
from openviking.storage.vectordb.collection.collection import Collection
diff --git a/openviking/storage/vectordb/service/__init__.py b/openviking/storage/vectordb/service/__init__.py
index 819b3465d..236633478 100644
--- a/openviking/storage/vectordb/service/__init__.py
+++ b/openviking/storage/vectordb/service/__init__.py
@@ -1,2 +1,2 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
diff --git a/openviking/storage/vectordb/service/api_fastapi.py b/openviking/storage/vectordb/service/api_fastapi.py
index 17c4445d7..95b20379b 100644
--- a/openviking/storage/vectordb/service/api_fastapi.py
+++ b/openviking/storage/vectordb/service/api_fastapi.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import os
import time
from dataclasses import asdict
diff --git a/openviking/storage/vectordb/service/app_models.py b/openviking/storage/vectordb/service/app_models.py
index b25bb8afd..81a622c60 100644
--- a/openviking/storage/vectordb/service/app_models.py
+++ b/openviking/storage/vectordb/service/app_models.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from typing import Any, Optional
from pydantic import BaseModel, Field
diff --git a/openviking/storage/vectordb/service/code.py b/openviking/storage/vectordb/service/code.py
index 709c191f7..10b3ac5ae 100644
--- a/openviking/storage/vectordb/service/code.py
+++ b/openviking/storage/vectordb/service/code.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from enum import Enum
diff --git a/openviking/storage/vectordb/service/server_fastapi.py b/openviking/storage/vectordb/service/server_fastapi.py
index 34574e603..ffddcab86 100644
--- a/openviking/storage/vectordb/service/server_fastapi.py
+++ b/openviking/storage/vectordb/service/server_fastapi.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""FastAPI server for VikingDB vector database service.
@@ -11,7 +11,7 @@ import asyncio
import random
import time
from contextlib import asynccontextmanager
-from typing import Dict, Any
+from typing import Any, Dict
import uvicorn
from fastapi import FastAPI, Request
@@ -28,19 +28,19 @@ _active_requests = 0
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Handle application startup and shutdown events.
-
+
Manages resource initialization and cleanup, ensuring graceful shutdown
by waiting for all active requests to complete.
-
+
Args:
app: The FastAPI application instance
"""
# Startup
logger.info("============ VikingDB Server Starting =============")
random.seed(time.time_ns())
-
+
yield
-
+
# Shutdown
logger.info("Waiting for active requests to complete...")
while _active_requests > 0:
@@ -61,31 +61,30 @@ app = FastAPI(
@app.exception_handler(VikingDBException)
async def vikingdb_exception_handler(request: Request, exc: VikingDBException) -> JSONResponse:
"""Handle VikingDB-specific exceptions.
-
+
Args:
request: The incoming HTTP request
exc: The VikingDBException that was raised
-
+
Returns:
JSONResponse with error details
"""
return JSONResponse(
- status_code=200,
- content=error_response(exc.message, exc.code.value, request=request)
+ status_code=200, content=error_response(exc.message, exc.code.value, request=request)
)
@app.middleware("http")
async def request_tracking_middleware(request: Request, call_next):
"""Middleware to track request processing time and active request count.
-
+
Increments active request counter, measures processing time,
and adds processing time header to response.
-
+
Args:
request: The incoming HTTP request
call_next: The next middleware/handler in the chain
-
+
Returns:
Response with added X-Process-Time header
"""
@@ -118,7 +117,7 @@ app.include_router(api_fastapi.search_router)
@app.get("/")
async def root() -> Dict[str, str]:
"""Root endpoint providing basic server information.
-
+
Returns:
Dict containing server name and version
"""
@@ -128,7 +127,7 @@ async def root() -> Dict[str, str]:
@app.get("/health")
async def health() -> Dict[str, Any]:
"""Health check endpoint for monitoring server status.
-
+
Returns:
Dict containing health status and current active request count
"""
@@ -140,4 +139,4 @@ if __name__ == "__main__":
logger.info("Starting VikingDB server on 0.0.0.0:5000")
uvicorn.run(app, host="0.0.0.0", port=5000, log_level="info")
except Exception as e:
- logger.error(f"Failed to start VikingDB server: {e}")
\ No newline at end of file
+ logger.error(f"Failed to start VikingDB server: {e}")
diff --git a/openviking/storage/vectordb/store/__init__.py b/openviking/storage/vectordb/store/__init__.py
index 819b3465d..236633478 100644
--- a/openviking/storage/vectordb/store/__init__.py
+++ b/openviking/storage/vectordb/store/__init__.py
@@ -1,2 +1,2 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
diff --git a/openviking/storage/vectordb/store/bytes_row.py b/openviking/storage/vectordb/store/bytes_row.py
index 8eaa2679d..58ae4c18d 100644
--- a/openviking/storage/vectordb/store/bytes_row.py
+++ b/openviking/storage/vectordb/store/bytes_row.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import struct
from dataclasses import dataclass
from enum import Enum
diff --git a/openviking/storage/vectordb/store/data.py b/openviking/storage/vectordb/store/data.py
index 07d8cc9de..cad0574bc 100644
--- a/openviking/storage/vectordb/store/data.py
+++ b/openviking/storage/vectordb/store/data.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import json
from dataclasses import dataclass, field
from typing import List
diff --git a/openviking/storage/vectordb/store/file_store.py b/openviking/storage/vectordb/store/file_store.py
index 95bd88432..abdd332a4 100644
--- a/openviking/storage/vectordb/store/file_store.py
+++ b/openviking/storage/vectordb/store/file_store.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import os
from pathlib import Path
from typing import Optional
diff --git a/openviking/storage/vectordb/store/local_store.py b/openviking/storage/vectordb/store/local_store.py
index 3b56a5dda..9f3728930 100644
--- a/openviking/storage/vectordb/store/local_store.py
+++ b/openviking/storage/vectordb/store/local_store.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from typing import List, Tuple, Union
import openviking.storage.vectordb.engine as engine
diff --git a/openviking/storage/vectordb/store/serializable.py b/openviking/storage/vectordb/store/serializable.py
index 1a8a1ae08..d8bc5ee1d 100644
--- a/openviking/storage/vectordb/store/serializable.py
+++ b/openviking/storage/vectordb/store/serializable.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Elegant serialization decorator: automatically generate schema and serialization methods from type annotations
"""
diff --git a/openviking/storage/vectordb/store/store.py b/openviking/storage/vectordb/store/store.py
index 732e86250..efbeefc0d 100644
--- a/openviking/storage/vectordb/store/store.py
+++ b/openviking/storage/vectordb/store/store.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from abc import ABC, abstractmethod
from enum import Enum
from typing import Any, List, Tuple, Union
diff --git a/openviking/storage/vectordb/store/store_manager.py b/openviking/storage/vectordb/store/store_manager.py
index 7a31b6ac8..403306e7a 100644
--- a/openviking/storage/vectordb/store/store_manager.py
+++ b/openviking/storage/vectordb/store/store_manager.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import time
from typing import List, Optional, Tuple
diff --git a/openviking/storage/vectordb/utils/__init__.py b/openviking/storage/vectordb/utils/__init__.py
index 819b3465d..236633478 100644
--- a/openviking/storage/vectordb/utils/__init__.py
+++ b/openviking/storage/vectordb/utils/__init__.py
@@ -1,2 +1,2 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
diff --git a/openviking/storage/vectordb/utils/api_utils.py b/openviking/storage/vectordb/utils/api_utils.py
index 58b31c052..53ab0e6c3 100644
--- a/openviking/storage/vectordb/utils/api_utils.py
+++ b/openviking/storage/vectordb/utils/api_utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from typing import Any, Dict, Optional
diff --git a/openviking/storage/vectordb/utils/config_utils.py b/openviking/storage/vectordb/utils/config_utils.py
index 785ca8df4..17ca2a066 100644
--- a/openviking/storage/vectordb/utils/config_utils.py
+++ b/openviking/storage/vectordb/utils/config_utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import os
from typing import Any, Dict, Optional
diff --git a/openviking/storage/vectordb/utils/constants.py b/openviking/storage/vectordb/utils/constants.py
index c5fd9fa89..583df6132 100644
--- a/openviking/storage/vectordb/utils/constants.py
+++ b/openviking/storage/vectordb/utils/constants.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Constants definition module
This module centralizes all constants used in VikingVectorIndex,
diff --git a/openviking/storage/vectordb/utils/data_processor.py b/openviking/storage/vectordb/utils/data_processor.py
index 0fa736ab9..7a75b1b1e 100644
--- a/openviking/storage/vectordb/utils/data_processor.py
+++ b/openviking/storage/vectordb/utils/data_processor.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Field type mapping and conversion helpers for scalar indexing."""
from __future__ import annotations
diff --git a/openviking/storage/vectordb/utils/data_utils.py b/openviking/storage/vectordb/utils/data_utils.py
index cb8db6fe3..dcf2bd384 100644
--- a/openviking/storage/vectordb/utils/data_utils.py
+++ b/openviking/storage/vectordb/utils/data_utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import json
import logging
from typing import Dict, List, Union
diff --git a/openviking/storage/vectordb/utils/dict_utils.py b/openviking/storage/vectordb/utils/dict_utils.py
index c76b14a9d..30313997e 100644
--- a/openviking/storage/vectordb/utils/dict_utils.py
+++ b/openviking/storage/vectordb/utils/dict_utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import threading
from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar
diff --git a/openviking/storage/vectordb/utils/file_utils.py b/openviking/storage/vectordb/utils/file_utils.py
index 95487fd98..5e4e5e5f8 100644
--- a/openviking/storage/vectordb/utils/file_utils.py
+++ b/openviking/storage/vectordb/utils/file_utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import logging
diff --git a/openviking/storage/vectordb/utils/id_generator.py b/openviking/storage/vectordb/utils/id_generator.py
index 39ae5b581..4b6b60fa6 100644
--- a/openviking/storage/vectordb/utils/id_generator.py
+++ b/openviking/storage/vectordb/utils/id_generator.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import os
import random
import threading
diff --git a/openviking/storage/vectordb/utils/logging_init.py b/openviking/storage/vectordb/utils/logging_init.py
index 5e3854fdc..87287d853 100644
--- a/openviking/storage/vectordb/utils/logging_init.py
+++ b/openviking/storage/vectordb/utils/logging_init.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""C++ logging initialization for vectordb engine."""
import sys
diff --git a/openviking/storage/vectordb/utils/stale_lock.py b/openviking/storage/vectordb/utils/stale_lock.py
index 2b4c61082..f73e97dea 100644
--- a/openviking/storage/vectordb/utils/stale_lock.py
+++ b/openviking/storage/vectordb/utils/stale_lock.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Stale RocksDB LOCK file cleanup for Windows.
On Windows, RocksDB LOCK files can persist after a process crash because
@@ -80,13 +80,9 @@ def clean_stale_rocksdb_locks(data_dir: str) -> int:
lock_path,
)
except OSError as exc:
- logger.warning(
- "Could not remove RocksDB LOCK %s: %s", lock_path, exc
- )
+ logger.warning("Could not remove RocksDB LOCK %s: %s", lock_path, exc)
if removed:
- logger.info(
- "Cleaned %d stale RocksDB LOCK file(s) under %s", removed, data_dir
- )
+ logger.info("Cleaned %d stale RocksDB LOCK file(s) under %s", removed, data_dir)
return removed
diff --git a/openviking/storage/vectordb/utils/str_to_uint64.py b/openviking/storage/vectordb/utils/str_to_uint64.py
index 65ad49c7d..e25ec2134 100644
--- a/openviking/storage/vectordb/utils/str_to_uint64.py
+++ b/openviking/storage/vectordb/utils/str_to_uint64.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import xxhash
diff --git a/openviking/storage/vectordb/utils/validation.py b/openviking/storage/vectordb/utils/validation.py
index 62ff3fff8..15b7f696f 100644
--- a/openviking/storage/vectordb/utils/validation.py
+++ b/openviking/storage/vectordb/utils/validation.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from enum import Enum
from typing import Annotated, Any, List, Literal, Optional
diff --git a/openviking/storage/vectordb/vectorize/__init__.py b/openviking/storage/vectordb/vectorize/__init__.py
index 819b3465d..236633478 100644
--- a/openviking/storage/vectordb/vectorize/__init__.py
+++ b/openviking/storage/vectordb/vectorize/__init__.py
@@ -1,2 +1,2 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
diff --git a/openviking/storage/vectordb/vectorize/base.py b/openviking/storage/vectordb/vectorize/base.py
index 3f980e5f4..88ad17641 100644
--- a/openviking/storage/vectordb/vectorize/base.py
+++ b/openviking/storage/vectordb/vectorize/base.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Base interface definition for vectorization module
"""
diff --git a/openviking/storage/vectordb/vectorize/vectorizer.py b/openviking/storage/vectordb/vectorize/vectorizer.py
index 222728f65..be3e2d043 100644
--- a/openviking/storage/vectordb/vectorize/vectorizer.py
+++ b/openviking/storage/vectordb/vectorize/vectorizer.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from typing import Any, Dict, List, Optional, Tuple, TypedDict
diff --git a/openviking/storage/vectordb/vectorize/vectorizer_factory.py b/openviking/storage/vectordb/vectorize/vectorizer_factory.py
index 9d510c1f1..4d3d4b639 100644
--- a/openviking/storage/vectordb/vectorize/vectorizer_factory.py
+++ b/openviking/storage/vectordb/vectorize/vectorizer_factory.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from enum import Enum
from typing import Any, Dict
diff --git a/openviking/storage/vectordb/vectorize/volcengine_vectorizer.py b/openviking/storage/vectordb/vectorize/volcengine_vectorizer.py
index 62e3349f0..4d62b5c92 100644
--- a/openviking/storage/vectordb/vectorize/volcengine_vectorizer.py
+++ b/openviking/storage/vectordb/vectorize/volcengine_vectorizer.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import json
import os
import time
diff --git a/openviking/storage/vectordb_adapters/__init__.py b/openviking/storage/vectordb_adapters/__init__.py
index 8446b64a6..6dadf2719 100644
--- a/openviking/storage/vectordb_adapters/__init__.py
+++ b/openviking/storage/vectordb_adapters/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""VectorDB backend collection adapter package."""
from .base import CollectionAdapter
diff --git a/openviking/storage/vectordb_adapters/base.py b/openviking/storage/vectordb_adapters/base.py
index e323e86d4..a831076fe 100644
--- a/openviking/storage/vectordb_adapters/base.py
+++ b/openviking/storage/vectordb_adapters/base.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Base adapter primitives for backend-specific vector collection operations."""
from __future__ import annotations
diff --git a/openviking/storage/vectordb_adapters/factory.py b/openviking/storage/vectordb_adapters/factory.py
index 6c11954c5..f86b733b2 100644
--- a/openviking/storage/vectordb_adapters/factory.py
+++ b/openviking/storage/vectordb_adapters/factory.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Adapter registry and factory entrypoints."""
from __future__ import annotations
diff --git a/openviking/storage/vectordb_adapters/http_adapter.py b/openviking/storage/vectordb_adapters/http_adapter.py
index 31082e9a5..ce9d96e61 100644
--- a/openviking/storage/vectordb_adapters/http_adapter.py
+++ b/openviking/storage/vectordb_adapters/http_adapter.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""HTTP backend collection adapter."""
from __future__ import annotations
diff --git a/openviking/storage/vectordb_adapters/local_adapter.py b/openviking/storage/vectordb_adapters/local_adapter.py
index ef0a3ae08..f8f7e18d5 100644
--- a/openviking/storage/vectordb_adapters/local_adapter.py
+++ b/openviking/storage/vectordb_adapters/local_adapter.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Local backend collection adapter."""
from __future__ import annotations
diff --git a/openviking/storage/vectordb_adapters/vikingdb_private_adapter.py b/openviking/storage/vectordb_adapters/vikingdb_private_adapter.py
index 43c6c9001..2342d57ba 100644
--- a/openviking/storage/vectordb_adapters/vikingdb_private_adapter.py
+++ b/openviking/storage/vectordb_adapters/vikingdb_private_adapter.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Private VikingDB backend collection adapter."""
from __future__ import annotations
diff --git a/openviking/storage/vectordb_adapters/volcengine_adapter.py b/openviking/storage/vectordb_adapters/volcengine_adapter.py
index b9e09cbe8..d06b0e84f 100644
--- a/openviking/storage/vectordb_adapters/volcengine_adapter.py
+++ b/openviking/storage/vectordb_adapters/volcengine_adapter.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Volcengine backend collection adapter."""
from __future__ import annotations
diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.py
index 0bf15ea51..fbefca0ed 100644
--- a/openviking/storage/viking_fs.py
+++ b/openviking/storage/viking_fs.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
VikingFS: OpenViking file system abstraction layer
diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.py
index 6be6dd1c5..22e4604bf 100644
--- a/openviking/storage/viking_vector_index_backend.py
+++ b/openviking/storage/viking_vector_index_backend.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""VikingDB storage backend for OpenViking."""
from __future__ import annotations
diff --git a/openviking/storage/vikingdb_manager.py b/openviking/storage/vikingdb_manager.py
index 1777b380b..899e6a1af 100644
--- a/openviking/storage/vikingdb_manager.py
+++ b/openviking/storage/vikingdb_manager.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
VikingDB Manager class that extends VikingVectorIndexBackend with queue management functionality.
"""
diff --git a/openviking/sync_client.py b/openviking/sync_client.py
index d6c333c1c..5b7e89ea4 100644
--- a/openviking/sync_client.py
+++ b/openviking/sync_client.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Synchronous OpenViking client implementation.
"""
diff --git a/openviking/telemetry/__init__.py b/openviking/telemetry/__init__.py
index 985beda4d..fb0625f44 100644
--- a/openviking/telemetry/__init__.py
+++ b/openviking/telemetry/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""OpenViking telemetry runtime and operation telemetry helpers."""
from .context import bind_telemetry, get_current_telemetry
diff --git a/openviking/telemetry/backends/__init__.py b/openviking/telemetry/backends/__init__.py
index 2e8ec32ee..a057f65b4 100644
--- a/openviking/telemetry/backends/__init__.py
+++ b/openviking/telemetry/backends/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Telemetry backend exports."""
from .memory import MemoryOperationTelemetry
diff --git a/openviking/telemetry/backends/memory.py b/openviking/telemetry/backends/memory.py
index 93c133f81..425c390f3 100644
--- a/openviking/telemetry/backends/memory.py
+++ b/openviking/telemetry/backends/memory.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Memory telemetry backend."""
from openviking.telemetry.operation import OperationTelemetry
diff --git a/openviking/telemetry/context.py b/openviking/telemetry/context.py
index 1384c95bc..9fe154f3c 100644
--- a/openviking/telemetry/context.py
+++ b/openviking/telemetry/context.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Telemetry context helpers."""
from __future__ import annotations
diff --git a/openviking/telemetry/execution.py b/openviking/telemetry/execution.py
index 32bf39dc4..8eda9e1c3 100644
--- a/openviking/telemetry/execution.py
+++ b/openviking/telemetry/execution.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Shared helpers for telemetry-wrapped operation execution."""
from __future__ import annotations
diff --git a/openviking/telemetry/operation.py b/openviking/telemetry/operation.py
index fc5777d39..520fd9543 100644
--- a/openviking/telemetry/operation.py
+++ b/openviking/telemetry/operation.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Operation-scoped telemetry primitives."""
from __future__ import annotations
diff --git a/openviking/telemetry/registry.py b/openviking/telemetry/registry.py
index 8cd7b0186..e1cfaef5b 100644
--- a/openviking/telemetry/registry.py
+++ b/openviking/telemetry/registry.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Telemetry registry helpers."""
from __future__ import annotations
diff --git a/openviking/telemetry/request.py b/openviking/telemetry/request.py
index 87e26c1a7..2b7eb4599 100644
--- a/openviking/telemetry/request.py
+++ b/openviking/telemetry/request.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Telemetry request parsing helpers."""
from __future__ import annotations
diff --git a/openviking/telemetry/resource_summary.py b/openviking/telemetry/resource_summary.py
index c578c270d..519799c96 100644
--- a/openviking/telemetry/resource_summary.py
+++ b/openviking/telemetry/resource_summary.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Resource-specific telemetry summary helpers."""
from __future__ import annotations
diff --git a/openviking/telemetry/runtime.py b/openviking/telemetry/runtime.py
index f6b6db5df..d88e7ec3f 100644
--- a/openviking/telemetry/runtime.py
+++ b/openviking/telemetry/runtime.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Telemetry runtime entrypoints."""
from __future__ import annotations
diff --git a/openviking/telemetry/snapshot.py b/openviking/telemetry/snapshot.py
index ed7755123..04a90eca7 100644
--- a/openviking/telemetry/snapshot.py
+++ b/openviking/telemetry/snapshot.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Telemetry snapshot model."""
from .operation import TelemetrySnapshot
diff --git a/openviking/utils/__init__.py b/openviking/utils/__init__.py
index 2ca0b3884..990f86bd3 100644
--- a/openviking/utils/__init__.py
+++ b/openviking/utils/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Utility functions and helpers."""
from openviking.utils.code_hosting_utils import (
diff --git a/openviking/utils/agfs_utils.py b/openviking/utils/agfs_utils.py
index 8db073d95..b0415a42d 100644
--- a/openviking/utils/agfs_utils.py
+++ b/openviking/utils/agfs_utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
AGFS Client utilities for creating and configuring AGFS clients.
"""
diff --git a/openviking/utils/circuit_breaker.py b/openviking/utils/circuit_breaker.py
index 6f9fbdc26..af511aebf 100644
--- a/openviking/utils/circuit_breaker.py
+++ b/openviking/utils/circuit_breaker.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Circuit breaker and error classification for API call protection."""
from __future__ import annotations
diff --git a/openviking/utils/code_hosting_utils.py b/openviking/utils/code_hosting_utils.py
index 300c0f457..c57e1fde0 100644
--- a/openviking/utils/code_hosting_utils.py
+++ b/openviking/utils/code_hosting_utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Utilities for code hosting platform URL parsing.
diff --git a/openviking/utils/embedding_utils.py b/openviking/utils/embedding_utils.py
index 68e4b060c..cf442cc0a 100644
--- a/openviking/utils/embedding_utils.py
+++ b/openviking/utils/embedding_utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Embedding utilities for OpenViking.
diff --git a/openviking/utils/media_processor.py b/openviking/utils/media_processor.py
index a9c7a0faa..7fa9e7cef 100644
--- a/openviking/utils/media_processor.py
+++ b/openviking/utils/media_processor.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Unified resource processor with strategy-based routing."""
import tempfile
diff --git a/openviking/utils/process_lock.py b/openviking/utils/process_lock.py
index f60452ae6..c8a92e959 100644
--- a/openviking/utils/process_lock.py
+++ b/openviking/utils/process_lock.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""PID-based advisory lock for data directory exclusivity.
Prevents multiple OpenViking processes from contending for the same data
diff --git a/openviking/utils/resource_processor.py b/openviking/utils/resource_processor.py
index 9f9ef43f9..320c6e51d 100644
--- a/openviking/utils/resource_processor.py
+++ b/openviking/utils/resource_processor.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Context Processor for OpenViking.
diff --git a/openviking/utils/skill_processor.py b/openviking/utils/skill_processor.py
index dedbcf4c1..d95be3cce 100644
--- a/openviking/utils/skill_processor.py
+++ b/openviking/utils/skill_processor.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Skill Processor for OpenViking.
diff --git a/openviking/utils/summarizer.py b/openviking/utils/summarizer.py
index dff099e62..805b7a3d2 100644
--- a/openviking/utils/summarizer.py
+++ b/openviking/utils/summarizer.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Summarizer for OpenViking.
Handles summarization and key information extraction.
diff --git a/openviking/utils/zip_safe.py b/openviking/utils/zip_safe.py
index 304687033..38ff9c6f3 100644
--- a/openviking/utils/zip_safe.py
+++ b/openviking/utils/zip_safe.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Safe ZIP extraction with Zip Slip protection."""
import os
diff --git a/openviking_cli/client/__init__.py b/openviking_cli/client/__init__.py
index e12673db8..7f5eb37f7 100644
--- a/openviking_cli/client/__init__.py
+++ b/openviking_cli/client/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""OpenViking Client module.
Provides client implementations for embedded (LocalClient) and HTTP (AsyncHTTPClient/SyncHTTPClient) modes.
diff --git a/openviking_cli/client/base.py b/openviking_cli/client/base.py
index baee3bf8d..89d85f5e7 100644
--- a/openviking_cli/client/base.py
+++ b/openviking_cli/client/base.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Base client interface for OpenViking.
Defines the abstract base class that both LocalClient and AsyncHTTPClient implement.
diff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.py
index 35d6bf26e..f17047e3a 100644
--- a/openviking_cli/client/http.py
+++ b/openviking_cli/client/http.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Async HTTP Client for OpenViking.
Implements BaseClient interface using HTTP calls to OpenViking Server.
diff --git a/openviking_cli/client/sync_http.py b/openviking_cli/client/sync_http.py
index c9e37e371..a75b7368c 100644
--- a/openviking_cli/client/sync_http.py
+++ b/openviking_cli/client/sync_http.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Synchronous HTTP Client for OpenViking.
Wraps AsyncHTTPClient with synchronous methods.
@@ -121,7 +121,9 @@ class SyncHTTPClient:
If both content and parts are provided, parts takes precedence.
"""
- return run_async(self._async_client.add_message(session_id, role, content, parts, created_at))
+ return run_async(
+ self._async_client.add_message(session_id, role, content, parts, created_at)
+ )
def get_task(self, task_id: str) -> Optional[Dict[str, Any]]:
"""Query background task status."""
diff --git a/openviking_cli/doctor.py b/openviking_cli/doctor.py
index e31c944e3..bcb231aaf 100644
--- a/openviking_cli/doctor.py
+++ b/openviking_cli/doctor.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""ov doctor - validate OpenViking subsystems and report actionable diagnostics.
Unlike ``ov health`` (which pings a running server), ``ov doctor`` checks
diff --git a/openviking_cli/exceptions.py b/openviking_cli/exceptions.py
index bcf73b2cd..476faf41d 100644
--- a/openviking_cli/exceptions.py
+++ b/openviking_cli/exceptions.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Unified exception classes for OpenViking.
diff --git a/openviking_cli/retrieve/types.py b/openviking_cli/retrieve/types.py
index 620595840..b3540011f 100644
--- a/openviking_cli/retrieve/types.py
+++ b/openviking_cli/retrieve/types.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Data types for OpenViking retrieval module.
"""
diff --git a/openviking_cli/server_bootstrap.py b/openviking_cli/server_bootstrap.py
index d086082f9..2385145af 100644
--- a/openviking_cli/server_bootstrap.py
+++ b/openviking_cli/server_bootstrap.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Lightweight entry point for openviking-server.
This module lives outside the ``openviking`` package so that importing it
diff --git a/openviking_cli/utils/__init__.py b/openviking_cli/utils/__init__.py
index c2ecc203b..0eccc53a1 100644
--- a/openviking_cli/utils/__init__.py
+++ b/openviking_cli/utils/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Utility functions and helpers."""
from openviking_cli.utils.async_utils import run_async
diff --git a/openviking_cli/utils/async_utils.py b/openviking_cli/utils/async_utils.py
index 9c4436dc3..86211773e 100644
--- a/openviking_cli/utils/async_utils.py
+++ b/openviking_cli/utils/async_utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Async helper utilities for running coroutines from sync code.
"""
diff --git a/openviking_cli/utils/cohere_rerank.py b/openviking_cli/utils/cohere_rerank.py
index a43ab074c..e930d8145 100644
--- a/openviking_cli/utils/cohere_rerank.py
+++ b/openviking_cli/utils/cohere_rerank.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Antigravity / Dico Angelo
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Cohere Rerank API Client.
diff --git a/openviking_cli/utils/config/__init__.py b/openviking_cli/utils/config/__init__.py
index 15ef612af..a42796dca 100644
--- a/openviking_cli/utils/config/__init__.py
+++ b/openviking_cli/utils/config/__init__.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from .agfs_config import AGFSConfig
from .config_loader import (
load_json_config,
diff --git a/openviking_cli/utils/config/agfs_config.py b/openviking_cli/utils/config/agfs_config.py
index 96c6bee23..bdbf80dcb 100644
--- a/openviking_cli/utils/config/agfs_config.py
+++ b/openviking_cli/utils/config/agfs_config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from enum import Enum
from typing import Optional
diff --git a/openviking_cli/utils/config/config_loader.py b/openviking_cli/utils/config/config_loader.py
index 7cdd950ff..4ad5a2079 100644
--- a/openviking_cli/utils/config/config_loader.py
+++ b/openviking_cli/utils/config/config_loader.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Configuration file loading utilities.
Provides a four-level resolution chain for locating config files:
diff --git a/openviking_cli/utils/config/config_utils.py b/openviking_cli/utils/config/config_utils.py
index 36d60330b..d6b9b3b25 100644
--- a/openviking_cli/utils/config/config_utils.py
+++ b/openviking_cli/utils/config/config_utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Shared helpers for config validation and error formatting."""
import difflib
diff --git a/openviking_cli/utils/config/consts.py b/openviking_cli/utils/config/consts.py
index 74e192046..4dfe1f95a 100644
--- a/openviking_cli/utils/config/consts.py
+++ b/openviking_cli/utils/config/consts.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Configuration constants for OpenViking."""
from pathlib import Path
diff --git a/openviking_cli/utils/config/embedding_config.py b/openviking_cli/utils/config/embedding_config.py
index 9082d7d3a..8caad66a9 100644
--- a/openviking_cli/utils/config/embedding_config.py
+++ b/openviking_cli/utils/config/embedding_config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from typing import Any, Optional, cast
from pydantic import BaseModel, Field, model_validator
diff --git a/openviking_cli/utils/config/encryption_config.py b/openviking_cli/utils/config/encryption_config.py
index fe52b2b47..c4f3e0c3e 100644
--- a/openviking_cli/utils/config/encryption_config.py
+++ b/openviking_cli/utils/config/encryption_config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from typing import Any, Dict, Optional
from pydantic import BaseModel, Field
diff --git a/openviking_cli/utils/config/log_config.py b/openviking_cli/utils/config/log_config.py
index 500d2a49a..c32fc0c26 100644
--- a/openviking_cli/utils/config/log_config.py
+++ b/openviking_cli/utils/config/log_config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from typing import Any, Dict
from pydantic import BaseModel, Field
diff --git a/openviking_cli/utils/config/memory_config.py b/openviking_cli/utils/config/memory_config.py
index 9f42ef425..b6889684f 100644
--- a/openviking_cli/utils/config/memory_config.py
+++ b/openviking_cli/utils/config/memory_config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from typing import Any, Dict
from pydantic import BaseModel, Field, field_validator
diff --git a/openviking_cli/utils/config/open_viking_config.py b/openviking_cli/utils/config/open_viking_config.py
index 58b1e9454..b769cb259 100644
--- a/openviking_cli/utils/config/open_viking_config.py
+++ b/openviking_cli/utils/config/open_viking_config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import json
import os
from pathlib import Path
diff --git a/openviking_cli/utils/config/ovcli_config.py b/openviking_cli/utils/config/ovcli_config.py
index 08ffff6fd..cb1b27068 100644
--- a/openviking_cli/utils/config/ovcli_config.py
+++ b/openviking_cli/utils/config/ovcli_config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Configuration schema and loader for ovcli.conf."""
from pathlib import Path
diff --git a/openviking_cli/utils/config/parser_config.py b/openviking_cli/utils/config/parser_config.py
index abd805c53..6c369915c 100644
--- a/openviking_cli/utils/config/parser_config.py
+++ b/openviking_cli/utils/config/parser_config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Unified parser configuration management for OpenViking.
diff --git a/openviking_cli/utils/config/rerank_config.py b/openviking_cli/utils/config/rerank_config.py
index ce11c237b..9d6c8e468 100644
--- a/openviking_cli/utils/config/rerank_config.py
+++ b/openviking_cli/utils/config/rerank_config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from typing import Optional
from pydantic import BaseModel, Field, model_validator
diff --git a/openviking_cli/utils/config/storage_config.py b/openviking_cli/utils/config/storage_config.py
index 739c1af6d..bcdb7eb5a 100644
--- a/openviking_cli/utils/config/storage_config.py
+++ b/openviking_cli/utils/config/storage_config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from pathlib import Path
from typing import Any, Dict
diff --git a/openviking_cli/utils/config/transaction_config.py b/openviking_cli/utils/config/transaction_config.py
index 86d153f8c..262758a1a 100644
--- a/openviking_cli/utils/config/transaction_config.py
+++ b/openviking_cli/utils/config/transaction_config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from pydantic import BaseModel, Field
diff --git a/openviking_cli/utils/config/vectordb_config.py b/openviking_cli/utils/config/vectordb_config.py
index 4aadac7d2..9a8f547b3 100644
--- a/openviking_cli/utils/config/vectordb_config.py
+++ b/openviking_cli/utils/config/vectordb_config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from typing import Any, Dict, Optional
from pydantic import BaseModel, Field, model_validator
diff --git a/openviking_cli/utils/config/vlm_config.py b/openviking_cli/utils/config/vlm_config.py
index 9e8260d29..dd67e7c2c 100644
--- a/openviking_cli/utils/config/vlm_config.py
+++ b/openviking_cli/utils/config/vlm_config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from typing import Any, Dict, List, Optional, Union
from pydantic import BaseModel, Field, model_validator
@@ -192,7 +192,9 @@ class VLMConfig(BaseModel):
messages: Optional[List[Dict[str, Any]]] = None,
) -> Union[str, Any]:
"""Get LLM completion asynchronously, max_retries=0 means no retry."""
- return await self.get_vlm_instance().get_completion_async(prompt, thinking, max_retries, tools, messages)
+ return await self.get_vlm_instance().get_completion_async(
+ prompt, thinking, max_retries, tools, messages
+ )
def is_available(self) -> bool:
"""Check if LLM is configured."""
@@ -207,7 +209,9 @@ class VLMConfig(BaseModel):
messages: Optional[List[Dict[str, Any]]] = None,
) -> Union[str, Any]:
"""Get LLM completion with images."""
- return self.get_vlm_instance().get_vision_completion(prompt, images, thinking, tools, messages)
+ return self.get_vlm_instance().get_vision_completion(
+ prompt, images, thinking, tools, messages
+ )
async def get_vision_completion_async(
self,
@@ -218,4 +222,6 @@ class VLMConfig(BaseModel):
messages: Optional[List[Dict[str, Any]]] = None,
) -> Union[str, Any]:
"""Get LLM completion with images asynchronously."""
- return await self.get_vlm_instance().get_vision_completion_async(prompt, images, thinking, tools, messages)
+ return await self.get_vlm_instance().get_vision_completion_async(
+ prompt, images, thinking, tools, messages
+ )
diff --git a/openviking_cli/utils/downloader.py b/openviking_cli/utils/downloader.py
index d9a73efa3..b654f37e7 100644
--- a/openviking_cli/utils/downloader.py
+++ b/openviking_cli/utils/downloader.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
URL downloader for OpenViking.
diff --git a/openviking_cli/utils/extractor.py b/openviking_cli/utils/extractor.py
index 5e936688c..1d53c5dad 100644
--- a/openviking_cli/utils/extractor.py
+++ b/openviking_cli/utils/extractor.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Content extractor types for OpenViking."""
from dataclasses import dataclass, field
diff --git a/openviking_cli/utils/llm.py b/openviking_cli/utils/llm.py
index 4840b5a1e..2f7e11e8c 100644
--- a/openviking_cli/utils/llm.py
+++ b/openviking_cli/utils/llm.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
LLM utilities for OpenViking.
diff --git a/openviking_cli/utils/logger.py b/openviking_cli/utils/logger.py
index 60a4683ec..629bb7d86 100644
--- a/openviking_cli/utils/logger.py
+++ b/openviking_cli/utils/logger.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Logging utilities for OpenViking.
"""
diff --git a/openviking_cli/utils/rerank.py b/openviking_cli/utils/rerank.py
index 06c2a0722..663a959aa 100644
--- a/openviking_cli/utils/rerank.py
+++ b/openviking_cli/utils/rerank.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
VikingDB Rerank API Client.
diff --git a/openviking_cli/utils/rerank_litellm.py b/openviking_cli/utils/rerank_litellm.py
index 9ef6efa50..ab8cc57d0 100644
--- a/openviking_cli/utils/rerank_litellm.py
+++ b/openviking_cli/utils/rerank_litellm.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
LiteLLM Rerank API Client.
"""
diff --git a/openviking_cli/utils/rerank_openai.py b/openviking_cli/utils/rerank_openai.py
index 28557b533..bdcc191b7 100644
--- a/openviking_cli/utils/rerank_openai.py
+++ b/openviking_cli/utils/rerank_openai.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
OpenAI-compatible Rerank API Client.
diff --git a/openviking_cli/utils/storage.py b/openviking_cli/utils/storage.py
index b612fd61b..f7ea728d7 100644
--- a/openviking_cli/utils/storage.py
+++ b/openviking_cli/utils/storage.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Storage path management for OpenViking.
diff --git a/openviking_cli/utils/uri.py b/openviking_cli/utils/uri.py
index 24b6805e7..61ef4d1c7 100644
--- a/openviking_cli/utils/uri.py
+++ b/openviking_cli/utils/uri.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
URI utilities for OpenViking.
diff --git a/pyproject.toml b/pyproject.toml
index e8d58a7fb..9cb87b39f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -16,7 +16,7 @@ requires-python = ">=3.10"
authors = [
{name = "ByteDance", email = "[email protected]"}
]
-license = { text = "Apache-2.0" }
+license = { text = "AGPL-3.0" }
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
diff --git a/src/abi3_engine_backend.cpp b/src/abi3_engine_backend.cpp
index 9eacc0795..68bd0f049 100644
--- a/src/abi3_engine_backend.cpp
+++ b/src/abi3_engine_backend.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#define Py_LIMITED_API 0x030A0000
#include <Python.h>
diff --git a/src/abi3_x86_caps.cpp b/src/abi3_x86_caps.cpp
index e2e522016..f6aff1a3d 100644
--- a/src/abi3_x86_caps.cpp
+++ b/src/abi3_x86_caps.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#define Py_LIMITED_API 0x030A0000
#include <Python.h>
diff --git a/src/common/ann_utils.h b/src/common/ann_utils.h
index e5df81ef8..347d8a28b 100644
--- a/src/common/ann_utils.h
+++ b/src/common/ann_utils.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <vector>
#include <memory>
diff --git a/src/common/io_utils.h b/src/common/io_utils.h
index d83979142..fa82e75ba 100644
--- a/src/common/io_utils.h
+++ b/src/common/io_utils.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <algorithm>
diff --git a/src/common/json_utils.h b/src/common/json_utils.h
index 2a224a9ae..fb069f466 100644
--- a/src/common/json_utils.h
+++ b/src/common/json_utils.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <map>
diff --git a/src/common/log_utils.cpp b/src/common/log_utils.cpp
index 97caa1a9e..adfaa4474 100644
--- a/src/common/log_utils.cpp
+++ b/src/common/log_utils.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "log_utils.h"
#include "spdlog/spdlog.h"
#include "spdlog/sinks/stdout_color_sinks.h"
diff --git a/src/common/log_utils.h b/src/common/log_utils.h
index b13f83b55..9da829d0b 100644
--- a/src/common/log_utils.h
+++ b/src/common/log_utils.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <string>
diff --git a/src/common/string_utils.h b/src/common/string_utils.h
index 3387fe421..d07f9d26d 100644
--- a/src/common/string_utils.h
+++ b/src/common/string_utils.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <string>
#include <vector>
diff --git a/src/common/zip_sort.h b/src/common/zip_sort.h
index 855ccf9c1..bb3aa1799 100644
--- a/src/common/zip_sort.h
+++ b/src/common/zip_sort.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <vector>
diff --git a/src/index/common_structs.h b/src/index/common_structs.h
index d68bfce9c..2c0fd5e69 100644
--- a/src/index/common_structs.h
+++ b/src/index/common_structs.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <vector>
diff --git a/src/index/detail/fields_dict.h b/src/index/detail/fields_dict.h
index dcc2266fa..be83b334b 100644
--- a/src/index/detail/fields_dict.h
+++ b/src/index/detail/fields_dict.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <iostream>
diff --git a/src/index/detail/index_manager_impl.cpp b/src/index/detail/index_manager_impl.cpp
index a87b68422..4d165d10a 100644
--- a/src/index/detail/index_manager_impl.cpp
+++ b/src/index/detail/index_manager_impl.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "index/detail/index_manager_impl.h"
#include <stdexcept>
#include <memory>
diff --git a/src/index/detail/index_manager_impl.h b/src/index/detail/index_manager_impl.h
index bd31d7ef0..d7b64019e 100644
--- a/src/index/detail/index_manager_impl.h
+++ b/src/index/detail/index_manager_impl.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include "index/index_manager.h"
#include "index/common_structs.h"
diff --git a/src/index/detail/meta/bruteforce_meta.h b/src/index/detail/meta/bruteforce_meta.h
index 94bb6a800..cf672d9fe 100644
--- a/src/index/detail/meta/bruteforce_meta.h
+++ b/src/index/detail/meta/bruteforce_meta.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <string>
#include <memory>
diff --git a/src/index/detail/meta/manager_meta.h b/src/index/detail/meta/manager_meta.h
index ebe881579..f9c551880 100644
--- a/src/index/detail/meta/manager_meta.h
+++ b/src/index/detail/meta/manager_meta.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <memory>
#include <fstream>
diff --git a/src/index/detail/meta/scalar_index_meta.cpp b/src/index/detail/meta/scalar_index_meta.cpp
index 35590718f..f3cfa3877 100644
--- a/src/index/detail/meta/scalar_index_meta.cpp
+++ b/src/index/detail/meta/scalar_index_meta.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "scalar_index_meta.h"
#include <fstream>
#include <sstream>
diff --git a/src/index/detail/meta/scalar_index_meta.h b/src/index/detail/meta/scalar_index_meta.h
index 82c49aa1e..7f4335000 100644
--- a/src/index/detail/meta/scalar_index_meta.h
+++ b/src/index/detail/meta/scalar_index_meta.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <string>
#include <vector>
diff --git a/src/index/detail/meta/vector_index_meta.cpp b/src/index/detail/meta/vector_index_meta.cpp
index a182bde0d..888f04316 100644
--- a/src/index/detail/meta/vector_index_meta.cpp
+++ b/src/index/detail/meta/vector_index_meta.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "index/detail/meta/vector_index_meta.h"
#include "spdlog/spdlog.h"
#include <rapidjson/writer.h>
diff --git a/src/index/detail/meta/vector_index_meta.h b/src/index/detail/meta/vector_index_meta.h
index 3b1322903..4c4a728fa 100644
--- a/src/index/detail/meta/vector_index_meta.h
+++ b/src/index/detail/meta/vector_index_meta.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <string>
#include "common/json_utils.h"
diff --git a/src/index/detail/scalar/bitmap_holder/bitmap.cpp b/src/index/detail/scalar/bitmap_holder/bitmap.cpp
index 2b66f0739..66279f09a 100644
--- a/src/index/detail/scalar/bitmap_holder/bitmap.cpp
+++ b/src/index/detail/scalar/bitmap_holder/bitmap.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "bitmap.h"
#include <algorithm>
diff --git a/src/index/detail/scalar/bitmap_holder/bitmap.h b/src/index/detail/scalar/bitmap_holder/bitmap.h
index 734b2a54c..6c76d6254 100644
--- a/src/index/detail/scalar/bitmap_holder/bitmap.h
+++ b/src/index/detail/scalar/bitmap_holder/bitmap.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <atomic>
#include <deque>
diff --git a/src/index/detail/scalar/bitmap_holder/bitmap_field_group.cpp b/src/index/detail/scalar/bitmap_holder/bitmap_field_group.cpp
index 3f9fc75bf..b2e429842 100644
--- a/src/index/detail/scalar/bitmap_holder/bitmap_field_group.cpp
+++ b/src/index/detail/scalar/bitmap_holder/bitmap_field_group.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "bitmap_field_group.h"
#include "index/detail/scalar/bitmap_holder/dir_index.h"
#include "common/io_utils.h"
diff --git a/src/index/detail/scalar/bitmap_holder/bitmap_field_group.h b/src/index/detail/scalar/bitmap_holder/bitmap_field_group.h
index 715a3c08e..eaa658eb9 100644
--- a/src/index/detail/scalar/bitmap_holder/bitmap_field_group.h
+++ b/src/index/detail/scalar/bitmap_holder/bitmap_field_group.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include "spdlog/spdlog.h"
diff --git a/src/index/detail/scalar/bitmap_holder/bitmap_utils.h b/src/index/detail/scalar/bitmap_holder/bitmap_utils.h
index ccc2eb5a2..5cc968e37 100644
--- a/src/index/detail/scalar/bitmap_holder/bitmap_utils.h
+++ b/src/index/detail/scalar/bitmap_holder/bitmap_utils.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <functional>
diff --git a/src/index/detail/scalar/bitmap_holder/dir_index.cpp b/src/index/detail/scalar/bitmap_holder/dir_index.cpp
index 3092d2e89..5c6817764 100644
--- a/src/index/detail/scalar/bitmap_holder/dir_index.cpp
+++ b/src/index/detail/scalar/bitmap_holder/dir_index.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "dir_index.h"
#include <deque>
#include <unordered_set>
diff --git a/src/index/detail/scalar/bitmap_holder/dir_index.h b/src/index/detail/scalar/bitmap_holder/dir_index.h
index 565c5b29d..1a7ef696a 100644
--- a/src/index/detail/scalar/bitmap_holder/dir_index.h
+++ b/src/index/detail/scalar/bitmap_holder/dir_index.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <algorithm>
#include <string>
diff --git a/src/index/detail/scalar/bitmap_holder/ranged_map.cpp b/src/index/detail/scalar/bitmap_holder/ranged_map.cpp
index 5365251d6..471ef5aca 100644
--- a/src/index/detail/scalar/bitmap_holder/ranged_map.cpp
+++ b/src/index/detail/scalar/bitmap_holder/ranged_map.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "ranged_map.h"
#include <algorithm>
#include "common/io_utils.h"
diff --git a/src/index/detail/scalar/bitmap_holder/ranged_map.h b/src/index/detail/scalar/bitmap_holder/ranged_map.h
index 4921455d8..cb75efb3f 100644
--- a/src/index/detail/scalar/bitmap_holder/ranged_map.h
+++ b/src/index/detail/scalar/bitmap_holder/ranged_map.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <limits.h>
#include <math.h>
diff --git a/src/index/detail/scalar/filter/filter_ops.cpp b/src/index/detail/scalar/filter/filter_ops.cpp
index 646824d7c..354d69cea 100644
--- a/src/index/detail/scalar/filter/filter_ops.cpp
+++ b/src/index/detail/scalar/filter/filter_ops.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "filter_ops.h"
#include "spdlog/spdlog.h"
diff --git a/src/index/detail/scalar/filter/filter_ops.h b/src/index/detail/scalar/filter/filter_ops.h
index db418ca5a..17b0813ea 100644
--- a/src/index/detail/scalar/filter/filter_ops.h
+++ b/src/index/detail/scalar/filter/filter_ops.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <algorithm>
diff --git a/src/index/detail/scalar/filter/op_base.cpp b/src/index/detail/scalar/filter/op_base.cpp
index 700eee8ea..6df642350 100644
--- a/src/index/detail/scalar/filter/op_base.cpp
+++ b/src/index/detail/scalar/filter/op_base.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "op_base.h"
#include "spdlog/spdlog.h"
diff --git a/src/index/detail/scalar/filter/op_base.h b/src/index/detail/scalar/filter/op_base.h
index 70b54ef3a..9e97e9622 100644
--- a/src/index/detail/scalar/filter/op_base.h
+++ b/src/index/detail/scalar/filter/op_base.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <limits.h>
diff --git a/src/index/detail/scalar/filter/sort_ops.cpp b/src/index/detail/scalar/filter/sort_ops.cpp
index e2a8e1eef..d117cec4e 100644
--- a/src/index/detail/scalar/filter/sort_ops.cpp
+++ b/src/index/detail/scalar/filter/sort_ops.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "sort_ops.h"
#include "spdlog/spdlog.h"
diff --git a/src/index/detail/scalar/filter/sort_ops.h b/src/index/detail/scalar/filter/sort_ops.h
index cd39b6b30..5e91cc24b 100644
--- a/src/index/detail/scalar/filter/sort_ops.h
+++ b/src/index/detail/scalar/filter/sort_ops.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <random>
diff --git a/src/index/detail/scalar/scalar_index.cpp b/src/index/detail/scalar/scalar_index.cpp
index ee36eabed..7a7b4dd4f 100644
--- a/src/index/detail/scalar/scalar_index.cpp
+++ b/src/index/detail/scalar/scalar_index.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "index/detail/scalar/scalar_index.h"
#include "spdlog/spdlog.h"
#include <ostream>
diff --git a/src/index/detail/scalar/scalar_index.h b/src/index/detail/scalar/scalar_index.h
index 7bdced0be..372ee7ac3 100644
--- a/src/index/detail/scalar/scalar_index.h
+++ b/src/index/detail/scalar/scalar_index.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <string>
diff --git a/src/index/detail/search_context.h b/src/index/detail/search_context.h
index 53b0b803e..17ec3c6ee 100644
--- a/src/index/detail/search_context.h
+++ b/src/index/detail/search_context.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <functional>
diff --git a/src/index/detail/vector/common/bruteforce.h b/src/index/detail/vector/common/bruteforce.h
index 5f53fab8d..cb3380691 100644
--- a/src/index/detail/vector/common/bruteforce.h
+++ b/src/index/detail/vector/common/bruteforce.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <vector>
diff --git a/src/index/detail/vector/common/quantization_int8.h b/src/index/detail/vector/common/quantization_int8.h
index 6b82b3478..b2f47c81c 100644
--- a/src/index/detail/vector/common/quantization_int8.h
+++ b/src/index/detail/vector/common/quantization_int8.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <cstdint>
diff --git a/src/index/detail/vector/common/quantizer.h b/src/index/detail/vector/common/quantizer.h
index 80c926b91..5c23b1448 100644
--- a/src/index/detail/vector/common/quantizer.h
+++ b/src/index/detail/vector/common/quantizer.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <cstring>
diff --git a/src/index/detail/vector/common/space_int8.h b/src/index/detail/vector/common/space_int8.h
index 36dda0e9e..f51d65fde 100644
--- a/src/index/detail/vector/common/space_int8.h
+++ b/src/index/detail/vector/common/space_int8.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include "vector_base.h"
diff --git a/src/index/detail/vector/common/space_ip.h b/src/index/detail/vector/common/space_ip.h
index 56c86910d..05b388aa7 100644
--- a/src/index/detail/vector/common/space_ip.h
+++ b/src/index/detail/vector/common/space_ip.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include "vector_base.h"
diff --git a/src/index/detail/vector/common/space_l2.h b/src/index/detail/vector/common/space_l2.h
index 773b642ec..ddee16ebd 100644
--- a/src/index/detail/vector/common/space_l2.h
+++ b/src/index/detail/vector/common/space_l2.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include "vector_base.h"
diff --git a/src/index/detail/vector/common/vector_base.h b/src/index/detail/vector/common/vector_base.h
index 27526d429..8bac1319a 100644
--- a/src/index/detail/vector/common/vector_base.h
+++ b/src/index/detail/vector/common/vector_base.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <cstdint>
diff --git a/src/index/detail/vector/sparse_retrieval/common.h b/src/index/detail/vector/sparse_retrieval/common.h
index 68ed86473..1f12d8675 100644
--- a/src/index/detail/vector/sparse_retrieval/common.h
+++ b/src/index/detail/vector/sparse_retrieval/common.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
namespace vectordb {
namespace sparse_common {
diff --git a/src/index/detail/vector/sparse_retrieval/sparse_data_holder.h b/src/index/detail/vector/sparse_retrieval/sparse_data_holder.h
index b2a73818f..f7685e961 100644
--- a/src/index/detail/vector/sparse_retrieval/sparse_data_holder.h
+++ b/src/index/detail/vector/sparse_retrieval/sparse_data_holder.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <vector>
diff --git a/src/index/detail/vector/sparse_retrieval/sparse_datapoint.cpp b/src/index/detail/vector/sparse_retrieval/sparse_datapoint.cpp
index be1f5429a..ba7d2bf5e 100644
--- a/src/index/detail/vector/sparse_retrieval/sparse_datapoint.cpp
+++ b/src/index/detail/vector/sparse_retrieval/sparse_datapoint.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "sparse_datapoint.h"
#include "common/io_utils.h"
diff --git a/src/index/detail/vector/sparse_retrieval/sparse_datapoint.h b/src/index/detail/vector/sparse_retrieval/sparse_datapoint.h
index 9843ae4e2..ede955776 100644
--- a/src/index/detail/vector/sparse_retrieval/sparse_datapoint.h
+++ b/src/index/detail/vector/sparse_retrieval/sparse_datapoint.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <cmath>
diff --git a/src/index/detail/vector/sparse_retrieval/sparse_dataset.h b/src/index/detail/vector/sparse_retrieval/sparse_dataset.h
index 57187ad55..f43379356 100644
--- a/src/index/detail/vector/sparse_retrieval/sparse_dataset.h
+++ b/src/index/detail/vector/sparse_retrieval/sparse_dataset.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include "index/detail/vector/sparse_retrieval/sparse_datapoint.h"
#include "spdlog/spdlog.h"
diff --git a/src/index/detail/vector/sparse_retrieval/sparse_distance_measure.h b/src/index/detail/vector/sparse_retrieval/sparse_distance_measure.h
index 3dea35b62..2bed15a7e 100644
--- a/src/index/detail/vector/sparse_retrieval/sparse_distance_measure.h
+++ b/src/index/detail/vector/sparse_retrieval/sparse_distance_measure.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <unordered_map>
diff --git a/src/index/detail/vector/sparse_retrieval/sparse_row_index.cpp b/src/index/detail/vector/sparse_retrieval/sparse_row_index.cpp
index d083f9747..3e44f83cf 100644
--- a/src/index/detail/vector/sparse_retrieval/sparse_row_index.cpp
+++ b/src/index/detail/vector/sparse_retrieval/sparse_row_index.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "index/detail/vector/sparse_retrieval/sparse_row_index.h"
#include "common/io_utils.h"
#include <algorithm>
diff --git a/src/index/detail/vector/sparse_retrieval/sparse_row_index.h b/src/index/detail/vector/sparse_retrieval/sparse_row_index.h
index b064ca331..27f3ea131 100644
--- a/src/index/detail/vector/sparse_retrieval/sparse_row_index.h
+++ b/src/index/detail/vector/sparse_retrieval/sparse_row_index.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include "spdlog/spdlog.h"
#include "common/zip_sort.h"
diff --git a/src/index/detail/vector/vector_index_adapter.h b/src/index/detail/vector/vector_index_adapter.h
index 10118b86b..accf73540 100644
--- a/src/index/detail/vector/vector_index_adapter.h
+++ b/src/index/detail/vector/vector_index_adapter.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <string>
diff --git a/src/index/detail/vector/vector_recall.h b/src/index/detail/vector/vector_recall.h
index 55ec79165..670de63ef 100644
--- a/src/index/detail/vector/vector_recall.h
+++ b/src/index/detail/vector/vector_recall.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <vector>
diff --git a/src/index/index_engine.cpp b/src/index/index_engine.cpp
index cccf6cc6f..7a5fd8c2c 100644
--- a/src/index/index_engine.cpp
+++ b/src/index/index_engine.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "index_engine.h"
#include "index/detail/index_manager_impl.h"
#include "index/detail/fields_dict.h"
diff --git a/src/index/index_engine.h b/src/index/index_engine.h
index ed136f7de..55d130db0 100644
--- a/src/index/index_engine.h
+++ b/src/index/index_engine.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <string>
diff --git a/src/index/index_manager.h b/src/index/index_manager.h
index bcadb3c2b..3da13ad99 100644
--- a/src/index/index_manager.h
+++ b/src/index/index_manager.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <string>
#include <vector>
diff --git a/src/store/common_structs.h b/src/store/common_structs.h
index 672f03b86..d16493fe2 100644
--- a/src/store/common_structs.h
+++ b/src/store/common_structs.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <string>
diff --git a/src/store/kv_store.h b/src/store/kv_store.h
index 56dedde8b..7ba551a43 100644
--- a/src/store/kv_store.h
+++ b/src/store/kv_store.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <string>
#include <vector>
diff --git a/src/store/persist_store.cpp b/src/store/persist_store.cpp
index 8d0b45d86..dcdf44373 100644
--- a/src/store/persist_store.cpp
+++ b/src/store/persist_store.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "persist_store.h"
#include "spdlog/spdlog.h"
#include <stdexcept>
diff --git a/src/store/persist_store.h b/src/store/persist_store.h
index b0ea5e019..cc878d751 100644
--- a/src/store/persist_store.h
+++ b/src/store/persist_store.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <string>
#include <vector>
diff --git a/src/store/volatile_store.cpp b/src/store/volatile_store.cpp
index a3ef09983..f3ee9e3ed 100644
--- a/src/store/volatile_store.cpp
+++ b/src/store/volatile_store.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "volatile_store.h"
#include "spdlog/spdlog.h"
#include <stdexcept>
diff --git a/src/store/volatile_store.h b/src/store/volatile_store.h
index 92d74b6d6..07d76e347 100644
--- a/src/store/volatile_store.h
+++ b/src/store/volatile_store.h
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#pragma once
#include <string>
#include <vector>
diff --git a/tests/__init__.py b/tests/__init__.py
index bf1d55fc2..77fca2f2b 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -1,3 +1,3 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""OpenViking Tests"""
diff --git a/tests/agfs/conftest.py b/tests/agfs/conftest.py
index 09467c001..0b41a614e 100644
--- a/tests/agfs/conftest.py
+++ b/tests/agfs/conftest.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import shutil
from pathlib import Path
diff --git a/tests/agfs/test_fs_binding.py b/tests/agfs/test_fs_binding.py
index 3e76ee8f4..f2a5554d2 100644
--- a/tests/agfs/test_fs_binding.py
+++ b/tests/agfs/test_fs_binding.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""AGFS Python Binding Tests for VikingFS interface
diff --git a/tests/agfs/test_fs_binding_s3.py b/tests/agfs/test_fs_binding_s3.py
index 802d4f6df..d199501d7 100644
--- a/tests/agfs/test_fs_binding_s3.py
+++ b/tests/agfs/test_fs_binding_s3.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""AGFS Python Binding Tests for VikingFS interface with S3 backend
diff --git a/tests/agfs/test_fs_local.py b/tests/agfs/test_fs_local.py
index 41ef07301..a92a1b551 100644
--- a/tests/agfs/test_fs_local.py
+++ b/tests/agfs/test_fs_local.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""AGFS Local Backend Tests for VikingFS interface"""
diff --git a/tests/agfs/test_fs_s3.py b/tests/agfs/test_fs_s3.py
index 00504fadd..eb75825e2 100644
--- a/tests/agfs/test_fs_s3.py
+++ b/tests/agfs/test_fs_s3.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""AGFS S3 Backend Tests for VikingFS interface with S3 client verification"""
diff --git a/tests/cli/conftest.py b/tests/cli/conftest.py
index 9e1f0c2c2..3958616dd 100644
--- a/tests/cli/conftest.py
+++ b/tests/cli/conftest.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""CLI fixtures that run against a real OpenViking server process."""
import json
diff --git a/tests/cli/test_doctor.py b/tests/cli/test_doctor.py
index e8f56dffc..428975053 100644
--- a/tests/cli/test_doctor.py
+++ b/tests/cli/test_doctor.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for ``ov doctor`` diagnostic checks."""
from __future__ import annotations
diff --git a/tests/client/__init__.py b/tests/client/__init__.py
index 738956b60..59338e06b 100644
--- a/tests/client/__init__.py
+++ b/tests/client/__init__.py
@@ -1,4 +1,4 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Client test module"""
diff --git a/tests/client/conftest.py b/tests/client/conftest.py
index fa74ce457..691851048 100644
--- a/tests/client/conftest.py
+++ b/tests/client/conftest.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Client test fixtures
diff --git a/tests/client/test_file_operations.py b/tests/client/test_file_operations.py
index a402e4af9..316f460ce 100644
--- a/tests/client/test_file_operations.py
+++ b/tests/client/test_file_operations.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""File operation tests"""
diff --git a/tests/client/test_filesystem.py b/tests/client/test_filesystem.py
index 7f325971d..b4611bbad 100644
--- a/tests/client/test_filesystem.py
+++ b/tests/client/test_filesystem.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Filesystem operation tests"""
diff --git a/tests/client/test_http_client_config.py b/tests/client/test_http_client_config.py
index ed6cb5a71..1f97f4735 100644
--- a/tests/client/test_http_client_config.py
+++ b/tests/client/test_http_client_config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import json
diff --git a/tests/client/test_http_client_local_upload.py b/tests/client/test_http_client_local_upload.py
index 4d2f771ea..1bed80a8b 100644
--- a/tests/client/test_http_client_local_upload.py
+++ b/tests/client/test_http_client_local_upload.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for client-side temp uploads when using localhost URLs."""
diff --git a/tests/client/test_import_export.py b/tests/client/test_import_export.py
index 2aaac8f78..e6d28bc9f 100644
--- a/tests/client/test_import_export.py
+++ b/tests/client/test_import_export.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Import/export tests"""
diff --git a/tests/client/test_lifecycle.py b/tests/client/test_lifecycle.py
index 677d4bbdb..93e4472a6 100644
--- a/tests/client/test_lifecycle.py
+++ b/tests/client/test_lifecycle.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Client lifecycle tests"""
diff --git a/tests/client/test_relations.py b/tests/client/test_relations.py
index 209838c5f..c968f5bb7 100644
--- a/tests/client/test_relations.py
+++ b/tests/client/test_relations.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Relation tests"""
diff --git a/tests/client/test_resource_management.py b/tests/client/test_resource_management.py
index 818427fea..4c44b7d69 100644
--- a/tests/client/test_resource_management.py
+++ b/tests/client/test_resource_management.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Resource management tests"""
diff --git a/tests/client/test_search.py b/tests/client/test_search.py
index ff661a25a..f24e161e8 100644
--- a/tests/client/test_search.py
+++ b/tests/client/test_search.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Search tests"""
diff --git a/tests/client/test_skill_management.py b/tests/client/test_skill_management.py
index 40ce64718..15e864126 100644
--- a/tests/client/test_skill_management.py
+++ b/tests/client/test_skill_management.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Skill management tests"""
diff --git a/tests/client/test_windows_path_handling.py b/tests/client/test_windows_path_handling.py
index a11239683..149e7311a 100644
--- a/tests/client/test_windows_path_handling.py
+++ b/tests/client/test_windows_path_handling.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for cross-platform path handling in ZIP operations."""
import tempfile
diff --git a/tests/conftest.py b/tests/conftest.py
index fafdc332b..1594feab7 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Global test fixtures"""
diff --git a/tests/engine/test_common.cpp b/tests/engine/test_common.cpp
index 5be308ef0..83be716c5 100644
--- a/tests/engine/test_common.cpp
+++ b/tests/engine/test_common.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include <iostream>
#include <vector>
#include <string>
diff --git a/tests/engine/test_index_engine.cpp b/tests/engine/test_index_engine.cpp
index 4b881f186..d24b12bfe 100644
--- a/tests/engine/test_index_engine.cpp
+++ b/tests/engine/test_index_engine.cpp
@@ -1,5 +1,5 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: AGPL-3.0
#include "index/index_engine.h"
#include <iostream>
#include <vector>
diff --git a/tests/eval/test_ragas_basic.py b/tests/eval/test_ragas_basic.py
index 348a93a49..9f3fe23f4 100644
--- a/tests/eval/test_ragas_basic.py
+++ b/tests/eval/test_ragas_basic.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import json
import tempfile
diff --git a/tests/eval/test_ragas_eval.py b/tests/eval/test_ragas_eval.py
index 8a92131b7..6ddef2a4b 100644
--- a/tests/eval/test_ragas_eval.py
+++ b/tests/eval/test_ragas_eval.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import json
from pathlib import Path
diff --git a/tests/eval/test_ragas_validation.py b/tests/eval/test_ragas_validation.py
index 272aed1ac..bcec15d7f 100644
--- a/tests/eval/test_ragas_validation.py
+++ b/tests/eval/test_ragas_validation.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Validation script for eval module using local_doc_example_glm5.jsonl.
"""
diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py
index 8d8d0c478..6695676b2 100644
--- a/tests/integration/__init__.py
+++ b/tests/integration/__init__.py
@@ -1,4 +1,4 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Integration test module"""
diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py
index 6ca667509..19f1d9488 100644
--- a/tests/integration/conftest.py
+++ b/tests/integration/conftest.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Shared fixtures for integration tests.
diff --git a/tests/integration/test_compressor_v2_e2e.py b/tests/integration/test_compressor_v2_e2e.py
index f01995e89..983024cbb 100644
--- a/tests/integration/test_compressor_v2_e2e.py
+++ b/tests/integration/test_compressor_v2_e2e.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
End-to-end test for SessionCompressorV2 (memory v2 templating system).
@@ -10,6 +10,7 @@ No need to worry about ov.conf - server uses its own config.
from dataclasses import asdict
from datetime import datetime
+
import pytest
import pytest_asyncio
@@ -31,45 +32,67 @@ def create_test_conversation_messages():
("assistant", "你好李明!很高兴认识你。能介绍一下你自己吗?"),
("user", "好的,我今年28岁,浙江杭州人,现在在网易工作,主要做后端开发。"),
("assistant", "很厉害!你在网易做什么项目?"),
-
# ===== 个人偏好 =====
- ("user", "我负责推荐系统相关的开发。对了,我喜欢喝咖啡,每天早上都要喝一杯美式咖啡,不加糖。"),
+ (
+ "user",
+ "我负责推荐系统相关的开发。对了,我喜欢喝咖啡,每天早上都要喝一杯美式咖啡,不加糖。",
+ ),
("assistant", "喝咖啡是个好习惯!你对咖啡有什么特别的偏好吗?"),
- ("user", "是的,我只喝浅烘焙的咖啡豆,而且必须是来自埃塞俄比亚的耶加雪菲,酸度要高一些的。"),
+ (
+ "user",
+ "是的,我只喝浅烘焙的咖啡豆,而且必须是来自埃塞俄比亚的耶加雪菲,酸度要高一些的。",
+ ),
("assistant", "很讲究啊!除了咖啡,你还有什么其他爱好吗?"),
-
# ===== 兴趣爱好 =====
- ("user", "我周末喜欢去爬山,北京周边的山我基本都爬过了,最喜欢的是香山,秋天的红叶特别美。"),
+ (
+ "user",
+ "我周末喜欢去爬山,北京周边的山我基本都爬过了,最喜欢的是香山,秋天的红叶特别美。",
+ ),
("assistant", "爬山很锻炼身体!你一般和谁一起去?"),
- ("user", "通常和我的女朋友张小红一起去,她也很喜欢户外运动,我们还一起加入了一个登山俱乐部。"),
-
+ (
+ "user",
+ "通常和我的女朋友张小红一起去,她也很喜欢户外运动,我们还一起加入了一个登山俱乐部。",
+ ),
# ===== 关系记忆 =====
("assistant", "真好!你们在一起多久了?"),
- ("user", "我们在一起三年了,是2023年的5月20日确定的关系,那天我们在西湖边散步,我向她表白的。"),
+ (
+ "user",
+ "我们在一起三年了,是2023年的5月20日确定的关系,那天我们在西湖边散步,我向她表白的。",
+ ),
("assistant", "很浪漫的日子!你们有计划结婚吗?"),
-
# ===== 事件/计划 =====
("user", "有的,我们打算明年春天结婚,婚礼地点初步定在杭州,具体时间还没定,大概是4月份。"),
("assistant", "恭喜恭喜!杭州是个美丽的城市。"),
- ("user", "是的,我老家就是杭州的,所以想在那里办婚礼。我们还打算去云南度蜜月,想去大理和丽江。"),
-
+ (
+ "user",
+ "是的,我老家就是杭州的,所以想在那里办婚礼。我们还打算去云南度蜜月,想去大理和丽江。",
+ ),
# ===== Agent/项目相关记忆 =====
("assistant", "听起来很棒!对了,你们现在在做什么项目?"),
("user", "我们团队正在做OpenViking项目,这是一个Agent原生的上下文数据库。"),
("assistant", "听起来很有意思!能详细说说吗?"),
- ("user", "好的,这个项目主要是帮助Agent更好地管理和记忆上下文信息,支持长期记忆的提取和存储。有两种主要的记忆类型:卡片(cards)用于知识笔记,采用Zettelkasten笔记法;事件(events)用于记录重要的决策和时间线。"),
+ (
+ "user",
+ "好的,这个项目主要是帮助Agent更好地管理和记忆上下文信息,支持长期记忆的提取和存储。有两种主要的记忆类型:卡片(cards)用于知识笔记,采用Zettelkasten笔记法;事件(events)用于记录重要的决策和时间线。",
+ ),
("assistant", "明白了!那技术架构是怎样的?"),
-
# ===== 技术知识/卡片 =====
- ("user", "技术上,我们使用MemoryReAct模式结合LLM来分析对话和生成记忆操作。v2版本使用了YAML配置的模板系统,比v1的8个固定类别更灵活。"),
+ (
+ "user",
+ "技术上,我们使用MemoryReAct模式结合LLM来分析对话和生成记忆操作。v2版本使用了YAML配置的模板系统,比v1的8个固定类别更灵活。",
+ ),
("assistant", "很有技术含量!你们团队有多少人?"),
-
# ===== 团队/组织信息 =====
- ("user", "我们团队现在有8个人,包括3个前端、4个后端,还有1个产品经理。产品经理叫王芳,她特别擅长用户体验设计。"),
+ (
+ "user",
+ "我们团队现在有8个人,包括3个前端、4个后端,还有1个产品经理。产品经理叫王芳,她特别擅长用户体验设计。",
+ ),
("assistant", "团队配置很齐全!你们平时怎么协作?"),
-
# ===== 工作习惯 =====
- ("user", "我们用敏捷开发,每周一上午开站会,周三进行技术评审,周五下午做代码回顾。我一般早上10点到公司,晚上8点左右下班。"),
+ (
+ "user",
+ "我们用敏捷开发,每周一上午开站会,周三进行技术评审,周五下午做代码回顾。我一般早上10点到公司,晚上8点左右下班。",
+ ),
("assistant", "很规律的工作节奏!"),
]
@@ -90,9 +113,7 @@ class TestCompressorV2EndToEnd:
@pytest.mark.integration
@pytest.mark.asyncio
- async def test_memory_v2_extraction_e2e(
- self, http_client: AsyncHTTPClient
- ):
+ async def test_memory_v2_extraction_e2e(self, http_client: AsyncHTTPClient):
"""
Test full end-to-end flow:
1. Create session with conversation
@@ -122,7 +143,9 @@ class TestCompressorV2EndToEnd:
for role, content in conversation:
parts = [TextPart(content)]
parts_dicts = [asdict(p) for p in parts]
- await client.add_message(session_id, role, parts=parts_dicts, created_at=session_time_str)
+ await client.add_message(
+ session_id, role, parts=parts_dicts, created_at=session_time_str
+ )
print(f"[{role}]: {content[:60]}...")
# 3. Commit session (this should trigger memory extraction)
@@ -166,7 +189,9 @@ class TestCompressorV2EndToEnd:
try:
# Try to list agent memories
- agent_memories = await client.ls(f"viking://agent/{agent_space}/memories", recursive=True)
+ agent_memories = await client.ls(
+ f"viking://agent/{agent_space}/memories", recursive=True
+ )
print(f"Agent memories entries: {len(agent_memories)}")
for entry in agent_memories[:20]: # Show first 20
print(f" - {entry['name']} ({'dir' if entry['isDir'] else 'file'})")
@@ -200,9 +225,7 @@ class TestCompressorV2EndToEnd:
@pytest.mark.integration
@pytest.mark.asyncio
- async def test_server_health(
- self, http_client: AsyncHTTPClient
- ):
+ async def test_server_health(self, http_client: AsyncHTTPClient):
"""Verify server is healthy"""
result = await http_client.health()
assert result is True
diff --git a/tests/integration/test_encryption_integration.py b/tests/integration/test_encryption_integration.py
index ecbdd5d47..411c5679f 100644
--- a/tests/integration/test_encryption_integration.py
+++ b/tests/integration/test_encryption_integration.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Encryption integration tests
diff --git a/tests/integration/test_full_workflow.py b/tests/integration/test_full_workflow.py
index b48385d74..569b70617 100644
--- a/tests/integration/test_full_workflow.py
+++ b/tests/integration/test_full_workflow.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Full workflow integration tests"""
diff --git a/tests/integration/test_gemini_e2e.py b/tests/integration/test_gemini_e2e.py
index c3e3507d0..1a19fee9b 100644
--- a/tests/integration/test_gemini_e2e.py
+++ b/tests/integration/test_gemini_e2e.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
End-to-end integration tests for GeminiDenseEmbedder.
Calls the real Gemini API — requires GOOGLE_API_KEY env var.
diff --git a/tests/integration/test_gemini_embedding_it.py b/tests/integration/test_gemini_embedding_it.py
index e02d1386f..79fa338f4 100644
--- a/tests/integration/test_gemini_embedding_it.py
+++ b/tests/integration/test_gemini_embedding_it.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Integration tests for GeminiDenseEmbedder — require real GOOGLE_API_KEY.
Run: GOOGLE_API_KEY=<key> pytest tests/integration/test_gemini_embedding_it.py -v
diff --git a/tests/integration/test_gemini_openviking_it.py b/tests/integration/test_gemini_openviking_it.py
index 15d19d0ee..a6946b75a 100644
--- a/tests/integration/test_gemini_openviking_it.py
+++ b/tests/integration/test_gemini_openviking_it.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
End-to-end integration tests for OpenViking add-memory + search using Gemini embeddings.
diff --git a/tests/integration/test_http_integration.py b/tests/integration/test_http_integration.py
index 96f41dc6f..0999c7c1e 100644
--- a/tests/integration/test_http_integration.py
+++ b/tests/integration/test_http_integration.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Integration tests for HTTP mode.
The server is automatically started via the ``server_url`` session fixture
diff --git a/tests/integration/test_vault_encryption_integration.py b/tests/integration/test_vault_encryption_integration.py
index 1055e2b39..3b8192d2a 100644
--- a/tests/integration/test_vault_encryption_integration.py
+++ b/tests/integration/test_vault_encryption_integration.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Vault encryption integration tests.
diff --git a/tests/integration/test_volcengine_kms_encryption_integration.py b/tests/integration/test_volcengine_kms_encryption_integration.py
index 5f0582c93..d95614311 100644
--- a/tests/integration/test_volcengine_kms_encryption_integration.py
+++ b/tests/integration/test_volcengine_kms_encryption_integration.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Volcengine KMS Encryption Integration Tests
diff --git a/tests/integration/test_watch_e2e.py b/tests/integration/test_watch_e2e.py
index a2c2ee871..61c51e36c 100644
--- a/tests/integration/test_watch_e2e.py
+++ b/tests/integration/test_watch_e2e.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""End-to-end tests for resource watch functionality."""
import asyncio
diff --git a/tests/misc/test_agfs_s3_config.py b/tests/misc/test_agfs_s3_config.py
index 0d85f0b73..2a17e9227 100644
--- a/tests/misc/test_agfs_s3_config.py
+++ b/tests/misc/test_agfs_s3_config.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import pytest
diff --git a/tests/misc/test_code_parser.py b/tests/misc/test_code_parser.py
index a5dbf621a..d4e6be59f 100644
--- a/tests/misc/test_code_parser.py
+++ b/tests/misc/test_code_parser.py
@@ -1,12 +1,11 @@
#!/usr/bin/env python3
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Test CodeRepositoryParser functionality and compliance with README.md requirements"""
import os
-import tempfile
-from pathlib import Path
import sys
+from pathlib import Path
# Add parent directory to path to import openviking
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
diff --git a/tests/misc/test_config_validation.py b/tests/misc/test_config_validation.py
index 89ad5d3ba..e2985ac52 100644
--- a/tests/misc/test_config_validation.py
+++ b/tests/misc/test_config_validation.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Test if config validators work correctly"""
import sys
diff --git a/tests/misc/test_debug_service.py b/tests/misc/test_debug_service.py
index 120d2e76b..fb7f1b36e 100644
--- a/tests/misc/test_debug_service.py
+++ b/tests/misc/test_debug_service.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Tests for DebugService and ObserverService.
"""
diff --git a/tests/misc/test_embedding_input_type.py b/tests/misc/test_embedding_input_type.py
index 339ed187f..ccb6d306d 100644
--- a/tests/misc/test_embedding_input_type.py
+++ b/tests/misc/test_embedding_input_type.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for non-symmetric query/document embedding passthrough.
Tests EmbeddingConfig's ability to create context-specific embedders:
diff --git a/tests/misc/test_extract_zip.py b/tests/misc/test_extract_zip.py
index 7be5ff871..d65a60a5f 100644
--- a/tests/misc/test_extract_zip.py
+++ b/tests/misc/test_extract_zip.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for CodeRepositoryParser._extract_zip Zip Slip protection."""
import io
diff --git a/tests/misc/test_mkdir.py b/tests/misc/test_mkdir.py
index ed0087059..d62e0efff 100644
--- a/tests/misc/test_mkdir.py
+++ b/tests/misc/test_mkdir.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for VikingFS.mkdir() — verifies the target directory is actually created."""
import contextvars
diff --git a/tests/misc/test_port_check.py b/tests/misc/test_port_check.py
index 1c7ac7e6b..87e6edab7 100644
--- a/tests/misc/test_port_check.py
+++ b/tests/misc/test_port_check.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for AGFSManager._check_port_available() socket leak fix."""
import gc
diff --git a/tests/misc/test_rerank_openai.py b/tests/misc/test_rerank_openai.py
index dd033b966..6a0c55f99 100644
--- a/tests/misc/test_rerank_openai.py
+++ b/tests/misc/test_rerank_openai.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for OpenAI-compatible rerank client and factory dispatch."""
from unittest.mock import MagicMock, patch
diff --git a/tests/misc/test_semantic_config.py b/tests/misc/test_semantic_config.py
index e68b768d0..1c9d2be52 100644
--- a/tests/misc/test_semantic_config.py
+++ b/tests/misc/test_semantic_config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for SemanticConfig, overview budget estimation, and memory chunking."""
diff --git a/tests/misc/test_tree_builder_dedup.py b/tests/misc/test_tree_builder_dedup.py
index 0610c60cc..7be179aae 100644
--- a/tests/misc/test_tree_builder_dedup.py
+++ b/tests/misc/test_tree_builder_dedup.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for TreeBuilder._resolve_unique_uri — duplicate filename auto-rename."""
import os
diff --git a/tests/misc/test_vikingdb_observer.py b/tests/misc/test_vikingdb_observer.py
index 4792892d4..aff41d6d4 100644
--- a/tests/misc/test_vikingdb_observer.py
+++ b/tests/misc/test_vikingdb_observer.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Test VikingDBObserver functionality
"""
diff --git a/tests/misc/test_vikingfs_find_without_rerank.py b/tests/misc/test_vikingfs_find_without_rerank.py
index 0b008aabd..76183892f 100644
--- a/tests/misc/test_vikingfs_find_without_rerank.py
+++ b/tests/misc/test_vikingfs_find_without_rerank.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Regression test for VikingFS.find without rerank configuration."""
import contextvars
diff --git a/tests/misc/test_vikingfs_uri_guard.py b/tests/misc/test_vikingfs_uri_guard.py
index f20513e34..6536cd533 100644
--- a/tests/misc/test_vikingfs_uri_guard.py
+++ b/tests/misc/test_vikingfs_uri_guard.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Regression tests for traversal-style URI rejection in VikingFS."""
import contextvars
diff --git a/tests/models/test_embedding_telemetry_usage.py b/tests/models/test_embedding_telemetry_usage.py
index 374128fde..12a0168de 100644
--- a/tests/models/test_embedding_telemetry_usage.py
+++ b/tests/models/test_embedding_telemetry_usage.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from __future__ import annotations
diff --git a/tests/models/test_vlm_strip_think_tags.py b/tests/models/test_vlm_strip_think_tags.py
index fd47fa1c4..c7a996cfb 100644
--- a/tests/models/test_vlm_strip_think_tags.py
+++ b/tests/models/test_vlm_strip_think_tags.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for stripping <think> reasoning tags from VLM responses."""
import pytest
diff --git a/tests/parse/__init__.py b/tests/parse/__init__.py
index d4ae00fa5..977e04624 100644
--- a/tests/parse/__init__.py
+++ b/tests/parse/__init__.py
@@ -1,4 +1,4 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Directory scan test module"""
diff --git a/tests/parse/test_add_directory.py b/tests/parse/test_add_directory.py
index 492f1c8d8..d5c7a3f1e 100644
--- a/tests/parse/test_add_directory.py
+++ b/tests/parse/test_add_directory.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Unit tests for DirectoryParser.
Verifies that:
diff --git a/tests/parse/test_ast_extractor.py b/tests/parse/test_ast_extractor.py
index d02517156..6924a7e8f 100644
--- a/tests/parse/test_ast_extractor.py
+++ b/tests/parse/test_ast_extractor.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for AST-based code skeleton extraction."""
from openviking.parse.parsers.code.ast.skeleton import ClassSkeleton, CodeSkeleton, FunctionSig
diff --git a/tests/parse/test_directory_parser_routing.py b/tests/parse/test_directory_parser_routing.py
index f7ebb6e3a..1b94774ba 100644
--- a/tests/parse/test_directory_parser_routing.py
+++ b/tests/parse/test_directory_parser_routing.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Isolated unit tests for directory-import parser routing and path mapping.
This script verifies **two independent concerns** without invoking the full
diff --git a/tests/parse/test_directory_scan.py b/tests/parse/test_directory_scan.py
index 3ec2fc66f..72781d2d6 100644
--- a/tests/parse/test_directory_scan.py
+++ b/tests/parse/test_directory_scan.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Unit tests for directory pre-scan validation module (RFC #83 T1)."""
from pathlib import Path
diff --git a/tests/parse/test_feishu_parser.py b/tests/parse/test_feishu_parser.py
index aece1739b..499b68df5 100644
--- a/tests/parse/test_feishu_parser.py
+++ b/tests/parse/test_feishu_parser.py
@@ -1,12 +1,12 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for FeishuParser."""
import asyncio
+from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
-from types import SimpleNamespace
from openviking.parse.parsers.feishu import FeishuParser
@@ -15,31 +15,58 @@ def _make_block(**kwargs):
"""Create a mock block object with only the specified attributes populated."""
# Start with all common attributes as None
defaults = {
- "block_id": "test_id", "block_type": 0, "parent_id": "parent_id",
- "children": None, "comment_ids": None, "add_ons": None,
- "page": None, "text": None, "heading1": None, "heading2": None,
- "heading3": None, "heading4": None, "heading5": None, "heading6": None,
- "heading7": None, "heading8": None, "heading9": None,
- "bullet": None, "ordered": None, "code": None, "quote": None,
- "todo": None, "divider": None, "image": None, "table": None,
- "table_cell": None, "quote_container": None, "sheet": None,
- "callout": None, "equation": None, "task": None,
+ "block_id": "test_id",
+ "block_type": 0,
+ "parent_id": "parent_id",
+ "children": None,
+ "comment_ids": None,
+ "add_ons": None,
+ "page": None,
+ "text": None,
+ "heading1": None,
+ "heading2": None,
+ "heading3": None,
+ "heading4": None,
+ "heading5": None,
+ "heading6": None,
+ "heading7": None,
+ "heading8": None,
+ "heading9": None,
+ "bullet": None,
+ "ordered": None,
+ "code": None,
+ "quote": None,
+ "todo": None,
+ "divider": None,
+ "image": None,
+ "table": None,
+ "table_cell": None,
+ "quote_container": None,
+ "sheet": None,
+ "callout": None,
+ "equation": None,
+ "task": None,
}
defaults.update(kwargs)
return SimpleNamespace(**defaults)
-def _make_text_content(text: str, bold=False, italic=False, inline_code=False,
- strikethrough=False, link_url=None):
+def _make_text_content(
+ text: str, bold=False, italic=False, inline_code=False, strikethrough=False, link_url=None
+):
"""Create a mock text content object with elements."""
style = SimpleNamespace(
- bold=bold, italic=italic, inline_code=inline_code,
+ bold=bold,
+ italic=italic,
+ inline_code=inline_code,
strikethrough=strikethrough,
link=SimpleNamespace(url=link_url) if link_url else None,
)
element = SimpleNamespace(
text_run=SimpleNamespace(content=text, text_element_style=style),
- mention_user=None, mention_doc=None, equation=None,
+ mention_user=None,
+ mention_doc=None,
+ equation=None,
)
return SimpleNamespace(elements=[element], style=None)
@@ -53,9 +80,7 @@ class TestParseFeishuUrl:
assert token == "doxcnABC123"
def test_wiki_url(self):
- doc_type, token = FeishuParser._parse_feishu_url(
- "https://example.feishu.cn/wiki/wikiXYZ"
- )
+ doc_type, token = FeishuParser._parse_feishu_url("https://example.feishu.cn/wiki/wikiXYZ")
assert doc_type == "wiki"
assert token == "wikiXYZ"
@@ -86,22 +111,24 @@ class TestParseFeishuUrl:
class TestIsFeishuUrl:
def test_feishu_docx(self):
from openviking.utils.media_processor import UnifiedResourceProcessor
- assert UnifiedResourceProcessor._is_feishu_url(
- "https://example.feishu.cn/docx/abc123"
- )
+
+ assert UnifiedResourceProcessor._is_feishu_url("https://example.feishu.cn/docx/abc123")
def test_larksuite(self):
from openviking.utils.media_processor import UnifiedResourceProcessor
+
assert UnifiedResourceProcessor._is_feishu_url(
"https://example.larksuite.com/sheets/abc123"
)
def test_non_feishu_url(self):
from openviking.utils.media_processor import UnifiedResourceProcessor
+
assert not UnifiedResourceProcessor._is_feishu_url("https://github.com/foo/bar")
def test_feishu_non_doc_path(self):
from openviking.utils.media_processor import UnifiedResourceProcessor
+
assert not UnifiedResourceProcessor._is_feishu_url(
"https://example.feishu.cn/profile/settings"
)
@@ -165,9 +192,7 @@ class TestBlockToMarkdown:
assert result == "---"
def test_image_block(self):
- block = _make_block(
- image=SimpleNamespace(token="img_token_123", alt="screenshot")
- )
+ block = _make_block(image=SimpleNamespace(token="img_token_123", alt="screenshot"))
result = self.parser._block_to_markdown(block, {}, {})
assert result == "![screenshot](feishu://image/img_token_123)"
@@ -190,25 +215,49 @@ class TestBlockToMarkdown:
class TestApplyTextStyle:
def test_bold(self):
- assert FeishuParser._apply_text_style("text", SimpleNamespace(
- bold=True, italic=False, strikethrough=False, inline_code=False, link=None
- )) == "**text**"
+ assert (
+ FeishuParser._apply_text_style(
+ "text",
+ SimpleNamespace(
+ bold=True, italic=False, strikethrough=False, inline_code=False, link=None
+ ),
+ )
+ == "**text**"
+ )
def test_italic(self):
- assert FeishuParser._apply_text_style("text", SimpleNamespace(
- bold=False, italic=True, strikethrough=False, inline_code=False, link=None
- )) == "*text*"
+ assert (
+ FeishuParser._apply_text_style(
+ "text",
+ SimpleNamespace(
+ bold=False, italic=True, strikethrough=False, inline_code=False, link=None
+ ),
+ )
+ == "*text*"
+ )
def test_inline_code(self):
- assert FeishuParser._apply_text_style("code", SimpleNamespace(
- bold=False, italic=False, strikethrough=False, inline_code=True, link=None
- )) == "`code`"
+ assert (
+ FeishuParser._apply_text_style(
+ "code",
+ SimpleNamespace(
+ bold=False, italic=False, strikethrough=False, inline_code=True, link=None
+ ),
+ )
+ == "`code`"
+ )
def test_link(self):
- result = FeishuParser._apply_text_style("click", SimpleNamespace(
- bold=False, italic=False, strikethrough=False, inline_code=False,
- link=SimpleNamespace(url="https://example.com"),
- ))
+ result = FeishuParser._apply_text_style(
+ "click",
+ SimpleNamespace(
+ bold=False,
+ italic=False,
+ strikethrough=False,
+ inline_code=False,
+ link=SimpleNamespace(url="https://example.com"),
+ ),
+ )
assert result == "[click](https://example.com)"
def test_empty_text(self):
@@ -267,15 +316,37 @@ def _mock_list_blocks_response(blocks, has_more=False, page_token=None):
def _make_sdk_block(block_id, parent_id="doc_id", **attrs):
"""Create a mock SDK block with all attributes defaulting to None."""
defaults = {
- "block_id": block_id, "block_type": 0, "parent_id": parent_id,
- "children": None, "comment_ids": None, "add_ons": None,
- "page": None, "text": None, "heading1": None, "heading2": None,
- "heading3": None, "heading4": None, "heading5": None, "heading6": None,
- "heading7": None, "heading8": None, "heading9": None,
- "bullet": None, "ordered": None, "code": None, "quote": None,
- "todo": None, "divider": None, "image": None, "table": None,
- "table_cell": None, "quote_container": None, "sheet": None,
- "callout": None, "equation": None, "task": None,
+ "block_id": block_id,
+ "block_type": 0,
+ "parent_id": parent_id,
+ "children": None,
+ "comment_ids": None,
+ "add_ons": None,
+ "page": None,
+ "text": None,
+ "heading1": None,
+ "heading2": None,
+ "heading3": None,
+ "heading4": None,
+ "heading5": None,
+ "heading6": None,
+ "heading7": None,
+ "heading8": None,
+ "heading9": None,
+ "bullet": None,
+ "ordered": None,
+ "code": None,
+ "quote": None,
+ "todo": None,
+ "divider": None,
+ "image": None,
+ "table": None,
+ "table_cell": None,
+ "quote_container": None,
+ "sheet": None,
+ "callout": None,
+ "equation": None,
+ "task": None,
}
defaults.update(attrs)
return SimpleNamespace(**defaults)
@@ -295,12 +366,21 @@ class TestParseDocxIntegration:
def test_parse_docx_basic(self):
"""Test basic document with page title, heading, and text."""
blocks = [
- _make_sdk_block("page_id", page=SimpleNamespace(
- elements=[SimpleNamespace(
- text_run=SimpleNamespace(content="My Document", text_element_style=None),
- mention_user=None, mention_doc=None, equation=None,
- )]
- )),
+ _make_sdk_block(
+ "page_id",
+ page=SimpleNamespace(
+ elements=[
+ SimpleNamespace(
+ text_run=SimpleNamespace(
+ content="My Document", text_element_style=None
+ ),
+ mention_user=None,
+ mention_doc=None,
+ equation=None,
+ )
+ ]
+ ),
+ ),
_make_sdk_block("h1_id", heading2=_make_text_content("Introduction")),
_make_sdk_block("t1_id", text=_make_text_content("Hello world")),
]
@@ -317,12 +397,21 @@ class TestParseDocxIntegration:
def test_parse_docx_with_pagination(self):
"""Test document fetching with multiple pages of blocks."""
page1_blocks = [
- _make_sdk_block("page_id", page=SimpleNamespace(
- elements=[SimpleNamespace(
- text_run=SimpleNamespace(content="Paginated Doc", text_element_style=None),
- mention_user=None, mention_doc=None, equation=None,
- )]
- )),
+ _make_sdk_block(
+ "page_id",
+ page=SimpleNamespace(
+ elements=[
+ SimpleNamespace(
+ text_run=SimpleNamespace(
+ content="Paginated Doc", text_element_style=None
+ ),
+ mention_user=None,
+ mention_doc=None,
+ equation=None,
+ )
+ ]
+ ),
+ ),
_make_sdk_block("t1_id", text=_make_text_content("Page 1 content")),
]
page2_blocks = [
@@ -371,24 +460,38 @@ class TestParseDocxIntegration:
def test_parse_docx_mixed_blocks(self):
"""Test document with various block types."""
blocks = [
- _make_sdk_block("page_id", page=SimpleNamespace(
- elements=[SimpleNamespace(
- text_run=SimpleNamespace(content="Report", text_element_style=None),
- mention_user=None, mention_doc=None, equation=None,
- )]
- )),
+ _make_sdk_block(
+ "page_id",
+ page=SimpleNamespace(
+ elements=[
+ SimpleNamespace(
+ text_run=SimpleNamespace(content="Report", text_element_style=None),
+ mention_user=None,
+ mention_doc=None,
+ equation=None,
+ )
+ ]
+ ),
+ ),
_make_sdk_block("h_id", heading2=_make_text_content("Section 1")),
_make_sdk_block("b1_id", bullet=_make_text_content("Item A")),
_make_sdk_block("b2_id", bullet=_make_text_content("Item B")),
_make_sdk_block("div_id", divider=SimpleNamespace()),
_make_sdk_block("q_id", quote=_make_text_content("A wise quote")),
- _make_sdk_block("code_id", code=SimpleNamespace(
- elements=[SimpleNamespace(
- text_run=SimpleNamespace(content="x = 1", text_element_style=None),
- mention_user=None, mention_doc=None, equation=None,
- )],
- style=SimpleNamespace(language="python"),
- )),
+ _make_sdk_block(
+ "code_id",
+ code=SimpleNamespace(
+ elements=[
+ SimpleNamespace(
+ text_run=SimpleNamespace(content="x = 1", text_element_style=None),
+ mention_user=None,
+ mention_doc=None,
+ equation=None,
+ )
+ ],
+ style=SimpleNamespace(language="python"),
+ ),
+ ),
]
response = _mock_list_blocks_response(blocks)
parser = self._make_parser_with_mock_client(response)
@@ -409,7 +512,9 @@ class TestParseDocxIntegration:
_make_sdk_block("page_id", page=SimpleNamespace(elements=[])),
_make_sdk_block("o1", ordered=_make_text_content("First")),
_make_sdk_block("o2", ordered=_make_text_content("Second")),
- _make_sdk_block("t1", text=_make_text_content("Break")), # Non-ordered block resets counter
+ _make_sdk_block(
+ "t1", text=_make_text_content("Break")
+ ), # Non-ordered block resets counter
_make_sdk_block("o3", ordered=_make_text_content("New first")),
]
response = _mock_list_blocks_response(blocks)
@@ -430,12 +535,19 @@ class TestParseAsyncIntegration:
parser = FeishuParser()
blocks = [
- _make_sdk_block("page_id", page=SimpleNamespace(
- elements=[SimpleNamespace(
- text_run=SimpleNamespace(content="Test Doc", text_element_style=None),
- mention_user=None, mention_doc=None, equation=None,
- )]
- )),
+ _make_sdk_block(
+ "page_id",
+ page=SimpleNamespace(
+ elements=[
+ SimpleNamespace(
+ text_run=SimpleNamespace(content="Test Doc", text_element_style=None),
+ mention_user=None,
+ mention_doc=None,
+ equation=None,
+ )
+ ]
+ ),
+ ),
_make_sdk_block("t1", text=_make_text_content("Content here")),
]
mock_client = MagicMock()
@@ -451,8 +563,10 @@ class TestParseAsyncIntegration:
with patch("openviking.parse.parsers.feishu.MarkdownParser") as MockMD:
mock_md_instance = MagicMock()
+
async def _mock_parse_content(*a, **kw):
return mock_md_result
+
mock_md_instance.parse_content = _mock_parse_content
MockMD.return_value = mock_md_instance
@@ -494,8 +608,10 @@ class TestParseAsyncIntegration:
with patch("openviking.parse.parsers.feishu.MarkdownParser") as MockMD:
mock_md_instance = MagicMock()
+
async def _mock_parse_content(*a, **kw):
return mock_md_result
+
mock_md_instance.parse_content = _mock_parse_content
MockMD.return_value = mock_md_instance
diff --git a/tests/parse/test_filename_safety.py b/tests/parse/test_filename_safety.py
index 9c81cc2e2..0d8b85919 100644
--- a/tests/parse/test_filename_safety.py
+++ b/tests/parse/test_filename_safety.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for filename safety: hash & shorten when names are too long (issue #171)."""
import hashlib
diff --git a/tests/parse/test_image_ocr.py b/tests/parse/test_image_ocr.py
index 5883ec0c8..c4cc573c8 100644
--- a/tests/parse/test_image_ocr.py
+++ b/tests/parse/test_image_ocr.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for OCR text extraction in ImageParser."""
import io
diff --git a/tests/parse/test_markdown_char_limit.py b/tests/parse/test_markdown_char_limit.py
index 502542f45..fb4221d4a 100644
--- a/tests/parse/test_markdown_char_limit.py
+++ b/tests/parse/test_markdown_char_limit.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for MarkdownParser hard character limit enforcement (max_section_chars)."""
from unittest.mock import AsyncMock, MagicMock, patch
diff --git a/tests/parse/test_markdown_filename_collision.py b/tests/parse/test_markdown_filename_collision.py
index a88651b1f..dc6b7ca4a 100644
--- a/tests/parse/test_markdown_filename_collision.py
+++ b/tests/parse/test_markdown_filename_collision.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for _generate_merged_filename uniqueness when headings collide."""
from openviking.parse.parsers.markdown import MarkdownParser
diff --git a/tests/parse/test_pdf_bookmark_extraction.py b/tests/parse/test_pdf_bookmark_extraction.py
index ea0fbcc1b..4f6fc97e2 100644
--- a/tests/parse/test_pdf_bookmark_extraction.py
+++ b/tests/parse/test_pdf_bookmark_extraction.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Tests for PDF bookmark/outline extraction in PDFParser.
diff --git a/tests/resource/__init__.py b/tests/resource/__init__.py
index f05613572..4464d6d71 100644
--- a/tests/resource/__init__.py
+++ b/tests/resource/__init__.py
@@ -1,3 +1,3 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for resource monitoring module."""
diff --git a/tests/resource/test_watch_manager.py b/tests/resource/test_watch_manager.py
index 50c089e94..4c7ca68e8 100644
--- a/tests/resource/test_watch_manager.py
+++ b/tests/resource/test_watch_manager.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Unit tests for WatchManager."""
import asyncio
diff --git a/tests/retrieve/test_hierarchical_retriever_rerank.py b/tests/retrieve/test_hierarchical_retriever_rerank.py
index 43ac04d6d..45af89ee6 100644
--- a/tests/retrieve/test_hierarchical_retriever_rerank.py
+++ b/tests/retrieve/test_hierarchical_retriever_rerank.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Hierarchical retriever rerank behavior tests."""
diff --git a/tests/retrieve/test_hierarchical_retriever_target_dirs.py b/tests/retrieve/test_hierarchical_retriever_target_dirs.py
index 019328bb5..6df26a238 100644
--- a/tests/retrieve/test_hierarchical_retriever_target_dirs.py
+++ b/tests/retrieve/test_hierarchical_retriever_target_dirs.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Hierarchical retriever target_directories tests."""
diff --git a/tests/retrieve/test_provenance.py b/tests/retrieve/test_provenance.py
index 7b36c6804..0178a94e1 100644
--- a/tests/retrieve/test_provenance.py
+++ b/tests/retrieve/test_provenance.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for search result provenance metadata."""
from __future__ import annotations
diff --git a/tests/server/__init__.py b/tests/server/__init__.py
index 819b3465d..236633478 100644
--- a/tests/server/__init__.py
+++ b/tests/server/__init__.py
@@ -1,2 +1,2 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
diff --git a/tests/server/conftest.py b/tests/server/conftest.py
index 6b3fce733..875ddb502 100644
--- a/tests/server/conftest.py
+++ b/tests/server/conftest.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Shared fixtures for OpenViking server tests."""
diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.py
index 725ad658d..d6b5c58e1 100644
--- a/tests/server/test_admin_api.py
+++ b/tests/server/test_admin_api.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for Admin API endpoints (openviking/server/routers/admin.py)."""
diff --git a/tests/server/test_api_content.py b/tests/server/test_api_content.py
index ee8d7cea3..f9a958088 100644
--- a/tests/server/test_api_content.py
+++ b/tests/server/test_api_content.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for content endpoints: read, abstract, overview."""
diff --git a/tests/server/test_api_filesystem.py b/tests/server/test_api_filesystem.py
index 3a0da611c..0c57b6ddb 100644
--- a/tests/server/test_api_filesystem.py
+++ b/tests/server/test_api_filesystem.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for filesystem endpoints: ls, tree, stat, mkdir, rm, mv."""
diff --git a/tests/server/test_api_key_manager.py b/tests/server/test_api_key_manager.py
index 22220c3fe..1055dd938 100644
--- a/tests/server/test_api_key_manager.py
+++ b/tests/server/test_api_key_manager.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for APIKeyManager (openviking/server/api_keys.py)."""
diff --git a/tests/server/test_api_local_input_security.py b/tests/server/test_api_local_input_security.py
index 910638c6e..8d7ec7c10 100644
--- a/tests/server/test_api_local_input_security.py
+++ b/tests/server/test_api_local_input_security.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Security tests for HTTP server local input handling."""
diff --git a/tests/server/test_api_observer.py b/tests/server/test_api_observer.py
index c69a80e9f..a7dbe3776 100644
--- a/tests/server/test_api_observer.py
+++ b/tests/server/test_api_observer.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for observer endpoints (/api/v1/observer/*)."""
diff --git a/tests/server/test_api_relations.py b/tests/server/test_api_relations.py
index d9942e277..106f9bd91 100644
--- a/tests/server/test_api_relations.py
+++ b/tests/server/test_api_relations.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for relations endpoints: get relations, link, unlink."""
diff --git a/tests/server/test_api_resources.py b/tests/server/test_api_resources.py
index c320e0f5a..2357fd5a4 100644
--- a/tests/server/test_api_resources.py
+++ b/tests/server/test_api_resources.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for resource management endpoints."""
diff --git a/tests/server/test_api_search.py b/tests/server/test_api_search.py
index ce33773c8..ecc4b5353 100644
--- a/tests/server/test_api_search.py
+++ b/tests/server/test_api_search.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for search endpoints: find, search, grep, glob."""
diff --git a/tests/server/test_api_sessions.py b/tests/server/test_api_sessions.py
index 4d497498d..2288884d8 100644
--- a/tests/server/test_api_sessions.py
+++ b/tests/server/test_api_sessions.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for session endpoints."""
diff --git a/tests/server/test_auth.py b/tests/server/test_auth.py
index 943309de3..0da9d42ea 100644
--- a/tests/server/test_auth.py
+++ b/tests/server/test_auth.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for multi-tenant authentication (openviking/server/auth.py)."""
diff --git a/tests/server/test_bot_proxy_auth.py b/tests/server/test_bot_proxy_auth.py
index 2f7f86442..977702500 100644
--- a/tests/server/test_bot_proxy_auth.py
+++ b/tests/server/test_bot_proxy_auth.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Regression tests for bot proxy endpoint auth enforcement."""
diff --git a/tests/server/test_error_scenarios.py b/tests/server/test_error_scenarios.py
index 2e283469c..a55ae336d 100644
--- a/tests/server/test_error_scenarios.py
+++ b/tests/server/test_error_scenarios.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for error scenarios: invalid JSON, missing fields, error mapping."""
diff --git a/tests/server/test_http_client_sdk.py b/tests/server/test_http_client_sdk.py
index 998f9668c..1d8418825 100644
--- a/tests/server/test_http_client_sdk.py
+++ b/tests/server/test_http_client_sdk.py
@@ -1,13 +1,14 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""SDK tests using AsyncHTTPClient against a real uvicorn server."""
+import asyncio
import io
import zipfile
-import asyncio
-import pytest_asyncio
+
import pytest
+import pytest_asyncio
from openviking_cli.client.http import AsyncHTTPClient
from openviking_cli.exceptions import FailedPreconditionError
diff --git a/tests/server/test_identity.py b/tests/server/test_identity.py
index e11d24aa9..0dc595da0 100644
--- a/tests/server/test_identity.py
+++ b/tests/server/test_identity.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for identity types (openviking/server/identity.py)."""
diff --git a/tests/server/test_prometheus_metrics.py b/tests/server/test_prometheus_metrics.py
index 4b2a422a1..2568cfe51 100644
--- a/tests/server/test_prometheus_metrics.py
+++ b/tests/server/test_prometheus_metrics.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for the Prometheus metrics exporter."""
@@ -120,9 +120,7 @@ class TestMetricsEndpoint:
assert resp.status_code == 404
async def test_metrics_enabled_returns_200(self):
- config = ServerConfig(
- telemetry=TelemetryConfig(prometheus=PrometheusConfig(enabled=True))
- )
+ config = ServerConfig(telemetry=TelemetryConfig(prometheus=PrometheusConfig(enabled=True)))
app = create_app(config=config, service=None)
# Simulate lifespan setting the observer on app.state
obs = PrometheusObserver()
diff --git a/tests/server/test_server_health.py b/tests/server/test_server_health.py
index 6086360cd..e6e076ad6 100644
--- a/tests/server/test_server_health.py
+++ b/tests/server/test_server_health.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for server infrastructure: health, system status, middleware, error handling."""
diff --git a/tests/service/test_resource_service_watch.py b/tests/service/test_resource_service_watch.py
index 7a0f18d50..b9ec947e4 100644
--- a/tests/service/test_resource_service_watch.py
+++ b/tests/service/test_resource_service_watch.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Integration tests for ResourceService watch functionality."""
from typing import AsyncGenerator
diff --git a/tests/service/test_watch_recovery.py b/tests/service/test_watch_recovery.py
index b1bed7df9..7f5a40821 100644
--- a/tests/service/test_watch_recovery.py
+++ b/tests/service/test_watch_recovery.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Integration tests for watch task recovery after service restart."""
import asyncio
diff --git a/tests/session/__init__.py b/tests/session/__init__.py
index 81c1808d8..a0b2d92f3 100644
--- a/tests/session/__init__.py
+++ b/tests/session/__init__.py
@@ -1,3 +1,3 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Session test module"""
diff --git a/tests/session/conftest.py b/tests/session/conftest.py
index 0bdaa426e..a5ad6c58f 100644
--- a/tests/session/conftest.py
+++ b/tests/session/conftest.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Session test fixtures"""
diff --git a/tests/session/memory/test_compressor_v2.py b/tests/session/memory/test_compressor_v2.py
index d3957da6d..85397a768 100644
--- a/tests/session/memory/test_compressor_v2.py
+++ b/tests/session/memory/test_compressor_v2.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Test for SessionCompressorV2.
@@ -8,7 +8,7 @@ Uses MockVikingFS and real VLM (from config).
import logging
from types import SimpleNamespace
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List
from unittest.mock import patch
import pytest
@@ -275,7 +275,6 @@ def create_test_conversation() -> List[Message]:
class TestCompressorV2:
"""Tests for SessionCompressorV2."""
-
@pytest.mark.asyncio
async def test_extract_long_term_memories_includes_latest_archive_overview(self):
"""Latest archive overview should be prepended to the v2 conversation context."""
@@ -294,6 +293,7 @@ class TestCompressorV2:
class DummyProvider:
def get_memory_schemas(self, ctx):
return []
+
return DummyProvider()
async def run(self):
@@ -331,7 +331,6 @@ class TestCompressorV2:
assert result == []
# Note: latest_archive_overview 功能已移除,测试需要更新
-
@pytest.mark.integration
@pytest.mark.asyncio
async def test_extract_long_term_memories(self):
diff --git a/tests/session/memory/test_json_stability.py b/tests/session/memory/test_json_stability.py
index cc7f2773d..550e0c65c 100644
--- a/tests/session/memory/test_json_stability.py
+++ b/tests/session/memory/test_json_stability.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Tests for JSON stable parsing utilities.
"""
@@ -7,19 +7,16 @@ Tests for JSON stable parsing utilities.
import json
from typing import List, Optional
-import pytest
from pydantic import BaseModel, Field
from openviking.session.memory.utils import (
- remove_json_trailing_content,
+ _get_arg_type,
+ _get_origin_type,
extract_json_content,
+ parse_json_with_stability,
parse_memory_file_with_fields,
+ remove_json_trailing_content,
value_fault_tolerance,
- parse_value_with_tolerance,
- parse_json_with_stability,
- _get_origin_type,
- _get_arg_type,
- _any_to_str,
)
@@ -28,55 +25,55 @@ class TestExtractJsonContent:
def test_removes_trailing_content_after_closing_brace(self):
"""Test that content after the last } is removed."""
- content = '''{"reasonning": "test", "write_uris": []}
+ content = """{"reasonning": "test", "write_uris": []}
-Note: This is a safety warning from the model.'''
+Note: This is a safety warning from the model."""
result = extract_json_content(content)
assert result == '{"reasonning": "test", "write_uris": []}'
def test_removes_trailing_content_after_closing_bracket(self):
"""Test that content after the last ] is removed."""
- content = '''[{"reasonning": "test"}]
+ content = """[{"reasonning": "test"}]
-Extra content after.'''
+Extra content after."""
result = extract_json_content(content)
assert result == '[{"reasonning": "test"}]'
def test_handles_leading_content_before_json(self):
"""Test that content before the first { is removed."""
- content = '''Here's the JSON:
-{"reasonning": "test", "write_uris": []}'''
+ content = """Here's the JSON:
+{"reasonning": "test", "write_uris": []}"""
result = extract_json_content(content)
assert result == '{"reasonning": "test", "write_uris": []}'
def test_handles_both_leading_and_trailing_content(self):
"""Test that both content before { and after } are removed."""
- content = '''Alright, let me analyze this.
+ content = """Alright, let me analyze this.
First, I need to create some memory entries.
{"reasonning": "test", "write_uris": [{"memory_type": "cards", "name": "test"}]}
-That's all for now.'''
+That's all for now."""
result = extract_json_content(content)
parsed = json.loads(result)
- assert parsed['reasonning'] == 'test'
- assert len(parsed['write_uris']) == 1
+ assert parsed["reasonning"] == "test"
+ assert len(parsed["write_uris"]) == 1
def test_preserves_nested_structures(self):
"""Test that nested structures are preserved correctly."""
- content = '''{"reasonning": "test", "write_uris": [{"memory_type": "preferences", "topic": "test"}]}
+ content = """{"reasonning": "test", "write_uris": [{"memory_type": "preferences", "topic": "test"}]}
-Trailing content.'''
+Trailing content."""
result = extract_json_content(content)
- assert 'Trailing' not in result
+ assert "Trailing" not in result
parsed = json.loads(result)
- assert parsed['reasonning'] == 'test'
- assert len(parsed['write_uris']) == 1
+ assert parsed["reasonning"] == "test"
+ assert len(parsed["write_uris"]) == 1
def test_empty_string_returns_empty(self):
"""Test empty string input returns empty string."""
- assert extract_json_content('') == ''
- assert extract_json_content(' ') == ' '
+ assert extract_json_content("") == ""
+ assert extract_json_content(" ") == " "
class TestRemoveJsonTrailingContent:
@@ -84,9 +81,9 @@ class TestRemoveJsonTrailingContent:
def test_alias_works(self):
"""Test that remove_json_trailing_content is an alias for extract_json_content."""
- content = '''Alright, let's see.
+ content = """Alright, let's see.
{"reasonning": "test"}
-And then some.'''
+And then some."""
result1 = extract_json_content(content)
result2 = remove_json_trailing_content(content)
assert result1 == result2
@@ -97,45 +94,45 @@ class TestValueFaultTolerance:
def test_none_string_converts_to_none(self):
"""Test 'None' string converts to None for non-str types."""
- assert value_fault_tolerance(int, 'None') is None
- assert value_fault_tolerance(List[str], 'None') is None
+ assert value_fault_tolerance(int, "None") is None
+ assert value_fault_tolerance(List[str], "None") is None
def test_none_string_remains_string_for_str_type(self):
"""Test 'None' remains as string when target type is str."""
- assert value_fault_tolerance(str, 'None') == 'None'
+ assert value_fault_tolerance(str, "None") == "None"
def test_list_converts_to_string(self):
"""Test list converts to comma-separated string for str type."""
- assert value_fault_tolerance(str, ['a', 'b', 'c']) == 'a,b,c'
+ assert value_fault_tolerance(str, ["a", "b", "c"]) == "a,b,c"
def test_dict_converts_to_json_string(self):
"""Test dict converts to JSON string for str type."""
- result = value_fault_tolerance(str, {'key': 'value'})
- assert 'key' in result
- assert 'value' in result
+ result = value_fault_tolerance(str, {"key": "value"})
+ assert "key" in result
+ assert "value" in result
def test_number_converts_to_string(self):
"""Test numbers convert to string for str type."""
- assert value_fault_tolerance(str, 42) == '42'
- assert value_fault_tolerance(str, 3.14) == '3.14'
- assert value_fault_tolerance(str, True) == 'True'
+ assert value_fault_tolerance(str, 42) == "42"
+ assert value_fault_tolerance(str, 3.14) == "3.14"
+ assert value_fault_tolerance(str, True) == "True"
def test_string_converts_to_int(self):
"""Test string converts to int for int type."""
- assert value_fault_tolerance(int, '42') == 42
+ assert value_fault_tolerance(int, "42") == 42
def test_string_converts_to_float(self):
"""Test string converts to float for float type."""
- assert value_fault_tolerance(float, '3.14') == 3.14
+ assert value_fault_tolerance(float, "3.14") == 3.14
def test_string_wraps_to_list(self):
"""Test string wraps in list for list type."""
- assert value_fault_tolerance(List[str], 'test') == ['test']
+ assert value_fault_tolerance(List[str], "test") == ["test"]
def test_dict_wraps_to_list(self):
"""Test dict wraps in list for list type."""
- result = value_fault_tolerance(List[dict], {'key': 'value'})
- assert result == [{'key': 'value'}]
+ result = value_fault_tolerance(List[dict], {"key": "value"})
+ assert result == [{"key": "value"}]
class TestTypeHelpers:
@@ -160,7 +157,7 @@ class TestParseJsonWithStability:
"""Tests for full five-layer stable JSON parsing."""
class TestModel(BaseModel):
- reasonning: str = ''
+ reasonning: str = ""
count: Optional[int] = None
tags: List[str] = Field(default_factory=list)
@@ -169,16 +166,16 @@ class TestParseJsonWithStability:
content = '{"reasonning": "test", "count": 42, "tags": ["a", "b"]}'
data, error = parse_json_with_stability(content, model_class=self.TestModel)
assert error is None
- assert data.reasonning == 'test'
+ assert data.reasonning == "test"
assert data.count == 42
- assert data.tags == ['a', 'b']
+ assert data.tags == ["a", "b"]
def test_handles_list_wrapped_response(self):
"""Test [{"..."}] is handled correctly."""
content = '[{"reasonning": "test", "count": 42}]'
data, error = parse_json_with_stability(content, model_class=self.TestModel)
assert error is None
- assert data.reasonning == 'test'
+ assert data.reasonning == "test"
def test_filters_extra_fields(self):
"""Test extra fields are filtered when expected_fields is provided."""
@@ -186,10 +183,10 @@ class TestParseJsonWithStability:
data, error = parse_json_with_stability(
content,
model_class=self.TestModel,
- expected_fields=['reasonning', 'count', 'tags'],
+ expected_fields=["reasonning", "count", "tags"],
)
assert error is None
- assert data.reasonning == 'test'
+ assert data.reasonning == "test"
assert data.count == 42
def test_returns_raw_dict_when_no_model_class(self):
@@ -198,30 +195,30 @@ class TestParseJsonWithStability:
data, error = parse_json_with_stability(content)
assert error is None
assert isinstance(data, dict)
- assert data['reasonning'] == 'test'
+ assert data["reasonning"] == "test"
def test_handles_trailing_content(self):
"""Test JSON with trailing content parses."""
- content = '''{"reasonning": "test"}
+ content = """{"reasonning": "test"}
Note: This is a safety warning.
-Please be careful with the output.'''
+Please be careful with the output."""
data, error = parse_json_with_stability(content, model_class=self.TestModel)
assert error is None
- assert data.reasonning == 'test'
+ assert data.reasonning == "test"
def test_handles_markdown_code_blocks(self):
"""Test JSON wrapped in markdown parses."""
- content = '''```json
+ content = """```json
{"reasonning": "test", "count": 42}
-```'''
+```"""
data, error = parse_json_with_stability(content, model_class=self.TestModel)
assert error is None
- assert data.reasonning == 'test'
+ assert data.reasonning == "test"
def test_returns_error_for_completely_invalid_content(self):
"""Test completely invalid content returns error."""
- content = 'This is not JSON at all'
+ content = "This is not JSON at all"
data, error = parse_json_with_stability(content)
assert data is None
assert error is not None
@@ -235,36 +232,38 @@ class TestMemoryOperationsIntegration:
topic: str
class SimpleOperations(BaseModel):
- reasonning: str = ''
- write_uris: List['TestMemoryOperationsIntegration.SimpleWriteOperation'] = Field(default_factory=list)
+ reasonning: str = ""
+ write_uris: List["TestMemoryOperationsIntegration.SimpleWriteOperation"] = Field(
+ default_factory=list
+ )
delete_uris: List[str] = Field(default_factory=list)
def test_parses_nested_write_operations(self):
"""Test nested write operations parse correctly."""
- content = '''{
+ content = """{
"reasonning": "Added user preferences",
"write_uris": [
{"memory_type": "preferences", "topic": "theme"},
{"memory_type": "preferences", "topic": "notifications"}
]
- }'''
+ }"""
data, error = parse_json_with_stability(content, model_class=self.SimpleOperations)
assert error is None
- assert data.reasonning == 'Added user preferences'
+ assert data.reasonning == "Added user preferences"
assert len(data.write_uris) == 2
- assert data.write_uris[0].topic == 'theme'
+ assert data.write_uris[0].topic == "theme"
def test_handles_string_instead_of_list_for_delete(self):
"""Test single string for delete_uris wraps to list via tolerance."""
# Note: This would need field-level tolerance applied
- content = '''{
+ content = """{
"reasonning": "Removed old memory",
"delete_uris": "viking://user/default/memories/old.md"
- }'''
+ }"""
# First parse as raw dict
data, error = parse_json_with_stability(content)
assert error is None
- assert data['delete_uris'] == 'viking://user/default/memories/old.md'
+ assert data["delete_uris"] == "viking://user/default/memories/old.md"
class TestParseMemoryFileWithFields:
@@ -272,7 +271,7 @@ class TestParseMemoryFileWithFields:
def test_parses_memory_fields_comment(self):
"""Test parsing MEMORY_FIELDS HTML comment."""
- content = '''<!-- MEMORY_FIELDS
+ content = """<!-- MEMORY_FIELDS
{
"tool_name": "web_search",
"static_desc": "Searches the web for information",
@@ -281,7 +280,7 @@ class TestParseMemoryFileWithFields:
}
-->
Here is the actual file content.
-It has multiple lines.'''
+It has multiple lines."""
result = parse_memory_file_with_fields(content)
assert result["tool_name"] == "web_search"
assert result["static_desc"] == "Searches the web for information"
@@ -305,10 +304,10 @@ It has multiple lines.'''
def test_handles_invalid_json_in_comment(self):
"""Test handles invalid JSON in MEMORY_FIELDS comment gracefully."""
# Use truly invalid JSON that even json_repair can't parse
- content = '''<!-- MEMORY_FIELDS
+ content = """<!-- MEMORY_FIELDS
not json at all, just random text
-->
-File content'''
+File content"""
result = parse_memory_file_with_fields(content)
assert "File content" in result["content"]
# No extra fields added
@@ -316,9 +315,9 @@ File content'''
def test_removes_comment_from_content(self):
"""Test that the comment is completely removed from content."""
- content = '''Before comment
+ content = """Before comment
<!-- MEMORY_FIELDS {"test": "value"} -->
-After comment'''
+After comment"""
result = parse_memory_file_with_fields(content)
assert "<!-- MEMORY_FIELDS" not in result["content"]
assert "Before comment" in result["content"]
@@ -327,8 +326,8 @@ After comment'''
def test_fields_on_same_line(self):
"""Test MEMORY_FIELDS on single line."""
- content = '''<!-- MEMORY_FIELDS {"tool_name": "test", "value": 42} -->
-Content'''
+ content = """<!-- MEMORY_FIELDS {"tool_name": "test", "value": 42} -->
+Content"""
result = parse_memory_file_with_fields(content)
assert result["tool_name"] == "test"
assert result["value"] == 42
diff --git a/tests/session/memory/test_memory_extractor_flow.py b/tests/session/memory/test_memory_extractor_flow.py
index 639241d5c..af6bde56b 100644
--- a/tests/session/memory/test_memory_extractor_flow.py
+++ b/tests/session/memory/test_memory_extractor_flow.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Test memory extraction flow with memory module components.
@@ -11,11 +11,10 @@ This test simulates the complete memory extraction workflow:
5. Apply operations via MemoryUpdater
"""
-from unittest.mock import AsyncMock, MagicMock, patch
-from typing import Any, Dict, List, Optional, Tuple
-from dataclasses import dataclass
-
import logging
+from typing import Any, Dict, List, Tuple
+from unittest.mock import patch
+
import pytest
# 让 openviking logger 的日志 propagate 到 pytest
@@ -30,7 +29,6 @@ logger = logging.getLogger(__name__)
from openviking.message import Message, TextPart
from openviking.server.identity import RequestContext, Role
from openviking.session.memory import (
- MemoryOperations,
ExtractLoop,
MemoryUpdater,
MemoryUpdateResult,
@@ -75,10 +73,7 @@ class MockVikingFS:
await self.mkdir(parent_uri)
# Write the file
- self._store[uri] = {
- "type": "file",
- "content": content
- }
+ self._store[uri] = {"type": "file", "content": content}
# Update parent directory's entries
if parent_uri and parent_uri in self._store:
@@ -88,17 +83,14 @@ class MockVikingFS:
"name": name,
"isDir": False,
"uri": uri,
- "abstract": content[:100] if content else ""
+ "abstract": content[:100] if content else "",
}
# Update or add to parent's children
parent = self._store[parent_uri]
if "children" not in parent:
parent["children"] = []
# Remove existing entry if present
- parent["children"] = [
- c for c in parent["children"]
- if c.get("name") != name
- ]
+ parent["children"] = [c for c in parent["children"] if c.get("name") != name]
parent["children"].append(file_entry)
async def ls(self, uri: str, **kwargs) -> List[Dict[str, Any]]:
@@ -119,25 +111,15 @@ class MockVikingFS:
await self.mkdir(parent_uri)
# Create this directory
- self._store[uri] = {
- "type": "dir",
- "children": []
- }
+ self._store[uri] = {"type": "dir", "children": []}
# Update parent directory's entries
if parent_uri and parent_uri in self._store:
name = self._get_name_from_uri(uri)
- dir_entry = {
- "name": name,
- "isDir": True,
- "uri": uri
- }
+ dir_entry = {"name": name, "isDir": True, "uri": uri}
parent = self._store[parent_uri]
# Remove existing entry if present
- parent["children"] = [
- c for c in parent["children"]
- if c.get("name") != name
- ]
+ parent["children"] = [c for c in parent["children"] if c.get("name") != name]
parent["children"].append(dir_entry)
async def rm(self, uri: str, **kwargs) -> None:
@@ -150,10 +132,7 @@ class MockVikingFS:
name = self._get_name_from_uri(uri)
if parent_uri and parent_uri in self._store:
parent = self._store[parent_uri]
- parent["children"] = [
- c for c in parent.get("children", [])
- if c.get("name") != name
- ]
+ parent["children"] = [c for c in parent.get("children", []) if c.get("name") != name]
# Remove the file/directory
del self._store[uri]
@@ -174,13 +153,10 @@ class MockVikingFS:
if entry.get("type") == "file":
name = self._get_name_from_uri(uri)
content = entry.get("content", "")
- if (query_lower in name.lower() or
- query_lower in content.lower()):
- memories.append({
- "uri": uri,
- "name": name,
- "abstract": content[:200] if content else ""
- })
+ if query_lower in name.lower() or query_lower in content.lower():
+ memories.append(
+ {"uri": uri, "name": name, "abstract": content[:200] if content else ""}
+ )
return {
"memories": memories,
@@ -221,21 +197,14 @@ class MockVikingFS:
if uri not in self._snapshot:
added[uri] = content
elif content != self._snapshot[uri]:
- modified[uri] = {
- "old": self._snapshot[uri],
- "new": content
- }
+ modified[uri] = {"old": self._snapshot[uri], "new": content}
# Check for deleted files
for uri in self._snapshot:
if uri not in current_files:
deleted[uri] = self._snapshot[uri]
- return {
- "added": added,
- "modified": modified,
- "deleted": deleted
- }
+ return {"added": added, "modified": modified, "deleted": deleted}
def print_diff(diff: Dict[str, Dict[str, str]]) -> None:
@@ -253,6 +222,7 @@ def print_diff(diff: Dict[str, Dict[str, str]]) -> None:
try:
from diff_match_patch import diff_match_patch
+
has_dmp = True
except ImportError:
has_dmp = False
@@ -291,7 +261,7 @@ def print_diff(diff: Dict[str, Dict[str, str]]) -> None:
_print_inline_diff(diffs, STYLE_DELETE, STYLE_INSERT, STYLE_RESET)
except Exception as e:
# Fallback to simple line-by-line comparison
- logger.exception("diff_match_patch fail",e)
+ logger.exception("diff_match_patch fail", e)
else:
logger.exception("has_dmp= False")
@@ -310,7 +280,9 @@ def print_diff(diff: Dict[str, Dict[str, str]]) -> None:
print("\n" + "=" * 80 + "\n")
-def _print_inline_diff(diffs: List[Tuple[int, str]], style_delete: str, style_insert: str, style_reset: str) -> None:
+def _print_inline_diff(
+ diffs: List[Tuple[int, str]], style_delete: str, style_insert: str, style_reset: str
+) -> None:
"""
Print character-level diff with inline colors.
@@ -323,14 +295,14 @@ def _print_inline_diff(diffs: List[Tuple[int, str]], style_delete: str, style_in
if op == 0: # 文本无差异:正常显示
output.append(f"{text}")
elif op == -1: # 文本删除:红色删除线
- output.append('\n'.join([f'{style_delete}{t}{style_reset}' for t in text.split('\n')]))
+ output.append("\n".join([f"{style_delete}{t}{style_reset}" for t in text.split("\n")]))
elif op == 1: # 文本新增:绿色
- output.append('\n'.join([f'{style_insert}{t}{style_reset}' for t in text.split('\n')]))
+ output.append("\n".join([f"{style_insert}{t}{style_reset}" for t in text.split("\n")]))
# 合并并打印最终结果,添加行号
formatted_text = "".join(output)
- for idx, line in enumerate(formatted_text.split('\n')):
- print(f" {idx+1}: {line}")
+ for idx, line in enumerate(formatted_text.split("\n")):
+ print(f" {idx + 1}: {line}")
def create_test_conversation() -> List[Message]:
@@ -344,7 +316,11 @@ def create_test_conversation() -> List[Message]:
msg1 = Message(
id="msg1",
role="user",
- parts=[TextPart("We're starting the memory extraction feature for the OpenViking project today. This project is an Agent-native context database.")],
+ parts=[
+ TextPart(
+ "We're starting the memory extraction feature for the OpenViking project today. This project is an Agent-native context database."
+ )
+ ],
)
messages.append(msg1)
@@ -352,7 +328,11 @@ def create_test_conversation() -> List[Message]:
msg2 = Message(
id="msg2",
role="assistant",
- parts=[TextPart("Great! The memory extraction feature is important. What technical approach are we planning to use?")],
+ parts=[
+ TextPart(
+ "Great! The memory extraction feature is important. What technical approach are we planning to use?"
+ )
+ ],
)
messages.append(msg2)
@@ -360,10 +340,12 @@ def create_test_conversation() -> List[Message]:
msg3 = Message(
id="msg3",
role="user",
- parts=[TextPart(
- "We've decided to use the ExtractLoop pattern, combined with LLMs to analyze conversations and generate memory operations. "
- "There are two main memory types: cards for knowledge cards (Zettelkasten note-taking method), and events for recording important events and decisions."
- )],
+ parts=[
+ TextPart(
+ "We've decided to use the ExtractLoop pattern, combined with LLMs to analyze conversations and generate memory operations. "
+ "There are two main memory types: cards for knowledge cards (Zettelkasten note-taking method), and events for recording important events and decisions."
+ )
+ ],
)
messages.append(msg3)
@@ -379,11 +361,13 @@ def create_test_conversation() -> List[Message]:
msg5 = Message(
id="msg5",
role="user",
- parts=[TextPart(
- "Cards are stored in viking://agent/{agent_space}/memories/cards, each card has name and content fields. "
- "Events are stored in viking://user/{user_space}/memories/events, each event has event_name, event_time, and content fields. "
- "Just now, we also decided to add diff-match-patch to print memory modification differences."
- )],
+ parts=[
+ TextPart(
+ "Cards are stored in viking://agent/{agent_space}/memories/cards, each card has name and content fields. "
+ "Events are stored in viking://user/{user_space}/memories/events, each event has event_name, event_time, and content fields. "
+ "Just now, we also decided to add diff-match-patch to print memory modification differences."
+ )
+ ],
)
messages.append(msg5)
@@ -455,13 +439,15 @@ def create_update_conversation() -> List[Message]:
msg1 = Message(
id="msg1",
role="user",
- parts=[TextPart(
- "I just looked at our OpenViking project card and need to correct it: "
- "OpenViking is not just a context database, it's an Agent-native memory system, "
- "supporting multi-level memory (L0/L1/L2) and incremental updates. "
- "Also, in the technical approach section, we not only use the ExtractLoop pattern, "
- "but also need to support schema-driven memory extraction."
- )],
+ parts=[
+ TextPart(
+ "I just looked at our OpenViking project card and need to correct it: "
+ "OpenViking is not just a context database, it's an Agent-native memory system, "
+ "supporting multi-level memory (L0/L1/L2) and incremental updates. "
+ "Also, in the technical approach section, we not only use the ExtractLoop pattern, "
+ "but also need to support schema-driven memory extraction."
+ )
+ ],
)
messages.append(msg1)
@@ -469,7 +455,11 @@ def create_update_conversation() -> List[Message]:
msg2 = Message(
id="msg2",
role="assistant",
- parts=[TextPart("Okay, I'll update the project card! Does the ExtractLoop pattern description need adjustment too?")],
+ parts=[
+ TextPart(
+ "Okay, I'll update the project card! Does the ExtractLoop pattern description need adjustment too?"
+ )
+ ],
)
messages.append(msg2)
@@ -477,13 +467,15 @@ def create_update_conversation() -> List[Message]:
msg3 = Message(
id="msg3",
role="user",
- parts=[TextPart(
- "Yes, the ExtractLoop card also needs updating: ExtractLoop is not just about analyzing conversations and generating operations, "
- "it's a complete orchestrator responsible for tool calling, LLM reasoning, and memory operation integration. "
- "Also, the event card that mentions 'Decided to use ExtractLoop pattern' "
- "needs to add the reason: because the ExtractLoop pattern can handle uncertainty well, "
- "verifying the correctness of memory operations through the ReAct flow."
- )],
+ parts=[
+ TextPart(
+ "Yes, the ExtractLoop card also needs updating: ExtractLoop is not just about analyzing conversations and generating operations, "
+ "it's a complete orchestrator responsible for tool calling, LLM reasoning, and memory operation integration. "
+ "Also, the event card that mentions 'Decided to use ExtractLoop pattern' "
+ "needs to add the reason: because the ExtractLoop pattern can handle uncertainty well, "
+ "verifying the correctness of memory operations through the ReAct flow."
+ )
+ ],
)
messages.append(msg3)
@@ -493,18 +485,15 @@ def create_update_conversation() -> List[Message]:
class TestMemoryExtractorFlow:
"""Test the complete memory extraction flow."""
-
@pytest.mark.integration
@pytest.mark.asyncio
async def test_full_flow_with_real_llm(self):
-
-
# Only mock VikingFS, everything else is real!
viking_fs = MockVikingFS()
initialize_openviking_config()
config = get_openviking_config()
vlm = config.vlm.get_vlm_instance()
- print(f'vlm={vlm}')
+ print(f"vlm={vlm}")
user = UserIdentifier.the_default_user()
ctx = RequestContext(user=user, role=Role.ROOT)
@@ -512,10 +501,7 @@ class TestMemoryExtractorFlow:
messages = create_test_conversation()
# Format conversation as string
- conversation_str = "\n".join([
- f"[{msg.role}]: {msg.content}"
- for msg in messages
- ])
+ conversation_str = "\n".join([f"[{msg.role}]: {msg.content}" for msg in messages])
print("-" * 60)
print("使用真实 LLM 测试完整流程(cards & events)...")
@@ -543,7 +529,7 @@ class TestMemoryExtractorFlow:
assert tools_used is not None
print("-" * 60)
- print(f"生成的操作:")
+ print("生成的操作:")
print(f" 写入:{len(operations.write_uris)}")
print(f" 编辑:{len(operations.edit_uris)}")
print(f" 删除:{len(operations.delete_uris)}")
@@ -551,14 +537,16 @@ class TestMemoryExtractorFlow:
print("-" * 60)
# Now test MemoryUpdater with the operations, mock get_viking_fs
- with patch('openviking.session.memory.memory_updater.get_viking_fs', return_value=viking_fs):
+ with patch(
+ "openviking.session.memory.memory_updater.get_viking_fs", return_value=viking_fs
+ ):
updater = MemoryUpdater()
# Pass the registry from orchestrator
result = await updater.apply_operations(operations, ctx, registry=orchestrator.registry)
assert isinstance(result, MemoryUpdateResult)
- print(f"已应用的操作:")
+ print("已应用的操作:")
print(f" 已写入:{len(result.written_uris)}")
print(f" 已编辑:{len(result.edited_uris)}")
print(f" 已删除:{len(result.deleted_uris)}")
@@ -570,9 +558,9 @@ class TestMemoryExtractorFlow:
print_diff(diff)
# Check that at least something happened (could be write/edit/delete depending on LLM)
- total_changes = (len(operations.write_uris) +
- len(operations.edit_uris) +
- len(operations.delete_uris))
+ total_changes = (
+ len(operations.write_uris) + len(operations.edit_uris) + len(operations.delete_uris)
+ )
print(f"LLM 建议的总变更数:{total_changes}")
@pytest.mark.integration
@@ -583,7 +571,7 @@ class TestMemoryExtractorFlow:
initialize_openviking_config()
config = get_openviking_config()
vlm = config.vlm.get_vlm_instance()
- print(f'vlm={vlm}')
+ print(f"vlm={vlm}")
# Only mock VikingFS, everything else is real!
viking_fs = MockVikingFS()
@@ -598,10 +586,7 @@ class TestMemoryExtractorFlow:
messages = create_update_conversation()
# Format conversation as string
- conversation_str = "\n".join([
- f"[{msg.role}]: {msg.content}"
- for msg in messages
- ])
+ conversation_str = "\n".join([f"[{msg.role}]: {msg.content}" for msg in messages])
print("=" * 60)
print("测试更新已有 cards 和 events...")
@@ -633,9 +618,9 @@ class TestMemoryExtractorFlow:
# Verify results
assert operations is not None
assert tools_used is not None
- print(f'operations={operations.model_dump_json(indent=4)}')
+ print(f"operations={operations.model_dump_json(indent=4)}")
print("=" * 60)
- print(f"生成的操作:")
+ print("生成的操作:")
print(f" 写入:{len(operations.write_uris)}")
print(f" 编辑:{len(operations.edit_uris)}")
print(f" 删除:{len(operations.delete_uris)}")
@@ -647,37 +632,39 @@ class TestMemoryExtractorFlow:
# Handle both dict and model objects
if isinstance(op, dict):
print(f" - memory_type: {op.get('memory_type', 'unknown')}")
- if 'fields' in op:
+ if "fields" in op:
print(f" - fields: {op['fields']}")
- if 'patches' in op:
+ if "patches" in op:
print(f" 补丁:{list(op['patches'].keys())}")
- if 'content' in op:
+ if "content" in op:
print(f" - content: {str(op['content'])[:100]}...")
else:
# Try to access as model attributes
- memory_type = getattr(op, 'memory_type', 'unknown')
+ memory_type = getattr(op, "memory_type", "unknown")
print(f" - memory_type: {memory_type}")
- fields = getattr(op, 'fields', None)
+ fields = getattr(op, "fields", None)
if fields:
print(f" - fields: {fields}")
- patches = getattr(op, 'patches', None)
+ patches = getattr(op, "patches", None)
if patches:
print(f" 补丁:{list(patches.keys())}")
- content = getattr(op, 'content', None)
+ content = getattr(op, "content", None)
if content:
print(f" - content: {str(content)[:100]}...")
print("=" * 60)
# Now test MemoryUpdater with the operations, mock get_viking_fs
- with patch('openviking.session.memory.memory_updater.get_viking_fs', return_value=viking_fs):
+ with patch(
+ "openviking.session.memory.memory_updater.get_viking_fs", return_value=viking_fs
+ ):
updater = MemoryUpdater()
# Pass the registry from orchestrator
result = await updater.apply_operations(operations, ctx, registry=orchestrator.registry)
assert isinstance(result, MemoryUpdateResult)
- print(f"已应用的操作:")
+ print("已应用的操作:")
print(f" 已写入:{len(result.written_uris)}")
print(f" 已编辑:{len(result.edited_uris)}")
print(f" 已删除:{len(result.deleted_uris)}")
@@ -715,9 +702,9 @@ class TestMemoryExtractorFlow:
print("=" * 60)
# Check that at least something happened (could be write/edit/delete depending on LLM)
- total_changes = (len(operations.write_uris) +
- len(operations.edit_uris) +
- len(operations.delete_uris))
+ total_changes = (
+ len(operations.write_uris) + len(operations.edit_uris) + len(operations.delete_uris)
+ )
print(f"LLM 建议的总变更数:{total_changes}")
def test_message_formatting(self):
@@ -728,5 +715,3 @@ class TestMemoryExtractorFlow:
assert messages[0].role == "user"
assert "OpenViking" in messages[0].content
assert "memory extraction" in messages[0].content
-
-
diff --git a/tests/session/memory/test_memory_patch.py b/tests/session/memory/test_memory_patch.py
index 904ee9028..24bf55978 100644
--- a/tests/session/memory/test_memory_patch.py
+++ b/tests/session/memory/test_memory_patch.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Tests for MemoryPatchHandler.
"""
@@ -123,7 +123,7 @@ Line 3 modified
>>>>>>> REPLACE
"""
result = self.handler.apply_content_patch(original, patch)
- assert ' if True:' in result
+ assert " if True:" in result
assert ' print("hello world")' in result
assert ' print("another line")' in result
diff --git a/tests/session/memory/test_memory_react.py b/tests/session/memory/test_memory_react.py
index e3e9462b7..740f080b7 100644
--- a/tests/session/memory/test_memory_react.py
+++ b/tests/session/memory/test_memory_react.py
@@ -1,22 +1,19 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Tests for memory ExtractLoop orchestrator.
"""
-import json
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
-from openviking.session.memory.extract_loop import (
- ExtractLoop,
-)
from openviking.session.memory.dataclass import (
MemoryTypeSchema,
- MemoryField,
)
-from openviking.session.memory.merge_op.base import FieldType, MergeOp
+from openviking.session.memory.extract_loop import (
+ ExtractLoop,
+)
class TestPreFetchFileFiltering:
@@ -133,8 +130,9 @@ class TestPreFetchFileFiltering:
if filename_template:
has_variables = "{" in filename_template and "}" in filename_template
- assert has_variables == expected_has_variables, \
+ assert has_variables == expected_has_variables, (
f"Template '{filename_template}': expected has_variables={expected_has_variables}"
+ )
class TestAllowedDirectoriesList:
@@ -157,7 +155,9 @@ class TestAllowedDirectoriesList:
def test_get_allowed_directories_list(self, mock_vlm, mock_viking_fs):
"""Test that allowed directories list is properly formatted."""
# Patch the registry loading so we can inject our own schemas
- with patch('openviking.session.memory.extract_loop.MemoryTypeRegistry') as mock_registry_cls:
+ with patch(
+ "openviking.session.memory.extract_loop.MemoryTypeRegistry"
+ ) as mock_registry_cls:
mock_registry = MagicMock()
# Create test schemas
@@ -180,9 +180,10 @@ class TestAllowedDirectoriesList:
mock_registry_cls.return_value = mock_registry
# Also patch schema_model_generator and schema_prompt_generator
- with patch('openviking.session.memory.extract_loop.SchemaModelGenerator') as mock_smg, \
- patch('openviking.session.memory.extract_loop.SchemaPromptGenerator') as mock_spg:
-
+ with (
+ patch("openviking.session.memory.extract_loop.SchemaModelGenerator") as mock_smg,
+ patch("openviking.session.memory.extract_loop.SchemaPromptGenerator") as mock_spg,
+ ):
mock_smg_instance = MagicMock()
mock_smg_instance.generate_all_models = MagicMock()
mock_smg_instance.get_llm_json_schema = MagicMock(return_value={})
@@ -198,4 +199,4 @@ class TestAllowedDirectoriesList:
# Verify the result contains the expected directories with variables replaced
assert "viking://user/default/memories/preferences" in result
- assert "viking://agent/default/memories/tools" in result
\ No newline at end of file
+ assert "viking://agent/default/memories/tools" in result
diff --git a/tests/session/memory/test_memory_react_system_prompt.py b/tests/session/memory/test_memory_react_system_prompt.py
index b1ccf112b..9348648ee 100644
--- a/tests/session/memory/test_memory_react_system_prompt.py
+++ b/tests/session/memory/test_memory_react_system_prompt.py
@@ -1,12 +1,9 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Test that provider instruction correctly instructs LLM.
"""
-import pytest
-from unittest.mock import MagicMock
-
from openviking.session.memory.session_extract_context_provider import SessionExtractContextProvider
@@ -22,8 +19,14 @@ class TestProviderInstruction:
instruction = provider.instruction()
# Check for critical instructions
- assert "Before editing ANY existing memory file, you MUST first read its complete content" in instruction
- assert "ONLY read URIs that are explicitly listed in ls tool results or returned by previous tool calls" in instruction
+ assert (
+ "Before editing ANY existing memory file, you MUST first read its complete content"
+ in instruction
+ )
+ assert (
+ "ONLY read URIs that are explicitly listed in ls tool results or returned by previous tool calls"
+ in instruction
+ )
def test_instruction_contains_output_language(self):
"""Test that instruction includes the output language setting."""
@@ -34,4 +37,4 @@ class TestProviderInstruction:
# Check that output language instruction is present
assert "Target Output Language" in instruction
- assert "All memory content MUST be written in" in instruction
\ No newline at end of file
+ assert "All memory content MUST be written in" in instruction
diff --git a/tests/session/memory/test_memory_tools.py b/tests/session/memory/test_memory_tools.py
index beda7d8bd..be0172a35 100644
--- a/tests/session/memory/test_memory_tools.py
+++ b/tests/session/memory/test_memory_tools.py
@@ -1,14 +1,13 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Tests for memory tools.
"""
-
from openviking.session.memory.tools import (
- MemorySearchTool,
MemoryLsTool,
MemoryReadTool,
+ MemorySearchTool,
get_tool,
get_tool_schemas,
list_tools,
diff --git a/tests/session/memory/test_memory_updater.py b/tests/session/memory/test_memory_updater.py
index ba0a39dd5..458b5f556 100644
--- a/tests/session/memory/test_memory_updater.py
+++ b/tests/session/memory/test_memory_updater.py
@@ -1,27 +1,22 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Tests for MemoryUpdater.
"""
-from datetime import datetime
-from unittest.mock import AsyncMock, MagicMock, patch
+
+from unittest.mock import AsyncMock, MagicMock
import pytest
+from openviking.session.memory.memory_type_registry import MemoryTypeRegistry
from openviking.session.memory.memory_updater import (
- MemoryUpdateResult,
MemoryUpdater,
-)
-from openviking.session.memory.memory_type_registry import MemoryTypeRegistry
-from openviking.session.memory.dataclass import (
- MemoryTypeSchema,
- MemoryField,
+ MemoryUpdateResult,
)
from openviking.session.memory.merge_op import (
SearchReplaceBlock,
StrPatch,
)
-from openviking.session.memory.merge_op.base import FieldType
from openviking.session.memory.utils import deserialize_full, serialize_with_metadata
@@ -139,23 +134,21 @@ Line 4"""
updater._get_viking_fs = MagicMock(return_value=mock_viking_fs)
# Create StrPatch
- patch = StrPatch(blocks=[
- SearchReplaceBlock(
- search="Line 2\nLine 3",
- replace="Line 2 modified\nLine 3 modified",
- start_line=2
- )
- ])
+ patch = StrPatch(
+ blocks=[
+ SearchReplaceBlock(
+ search="Line 2\nLine 3",
+ replace="Line 2 modified\nLine 3 modified",
+ start_line=2,
+ )
+ ]
+ )
# Mock request context
mock_ctx = MagicMock()
# Apply edit
- await updater._apply_edit(
- {"content": patch},
- "viking://test/test.md",
- mock_ctx
- )
+ await updater._apply_edit({"content": patch}, "viking://test/test.md", mock_ctx)
# Verify
assert written_content is not None
@@ -192,11 +185,7 @@ Goodbye"""
# StrPatch as dict (this is what JSON parsing gives us)
patch_dict = {
"blocks": [
- {
- "search": "This is a test",
- "replace": "This has been modified",
- "start_line": 2
- }
+ {"search": "This is a test", "replace": "This has been modified", "start_line": 2}
]
}
@@ -204,11 +193,7 @@ Goodbye"""
mock_ctx = MagicMock()
# Apply edit
- await updater._apply_edit(
- {"content": patch_dict},
- "viking://test/test.md",
- mock_ctx
- )
+ await updater._apply_edit({"content": patch_dict}, "viking://test/test.md", mock_ctx)
# Verify
assert written_content is not None
@@ -246,11 +231,7 @@ Goodbye"""
mock_ctx = MagicMock()
# Apply edit
- await updater._apply_edit(
- {"content": new_content},
- "viking://test/test.md",
- mock_ctx
- )
+ await updater._apply_edit({"content": new_content}, "viking://test/test.md", mock_ctx)
# Verify
assert written_content is not None
diff --git a/tests/session/memory/test_memory_utils.py b/tests/session/memory/test_memory_utils.py
index fcf73ecd3..9d26e40be 100644
--- a/tests/session/memory/test_memory_utils.py
+++ b/tests/session/memory/test_memory_utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Tests for memory utilities - URI generation, etc.
"""
@@ -8,9 +8,10 @@ import pytest
from openviking.session.memory.dataclass import (
MemoryField,
- MemoryTypeSchema,
MemoryOperations,
+ MemoryTypeSchema,
)
+from openviking.session.memory.memory_type_registry import MemoryTypeRegistry
from openviking.session.memory.merge_op.base import FieldType, MergeOp
from openviking.session.memory.utils import (
collect_allowed_directories,
@@ -22,7 +23,6 @@ from openviking.session.memory.utils import (
resolve_all_operations,
validate_uri_template,
)
-from openviking.session.memory.memory_type_registry import MemoryTypeRegistry
class TestUriGeneration:
@@ -226,7 +226,9 @@ class TestUriValidation:
),
]
- dirs = collect_allowed_directories([s for s in schemas if s.enabled], user_space="default", agent_space="default")
+ dirs = collect_allowed_directories(
+ [s for s in schemas if s.enabled], user_space="default", agent_space="default"
+ )
assert dirs == {
"viking://user/default/memories/preferences",
@@ -245,7 +247,9 @@ class TestUriValidation:
),
]
- patterns = collect_allowed_path_patterns(schemas, user_space="default", agent_space="default")
+ patterns = collect_allowed_path_patterns(
+ schemas, user_space="default", agent_space="default"
+ )
assert patterns == {
"viking://user/default/memories/preferences/{topic}.md",
@@ -259,23 +263,32 @@ class TestUriValidation:
}
allowed_patterns = set()
- assert is_uri_allowed(
- "viking://user/default/memories/preferences/test.md",
- allowed_dirs,
- allowed_patterns,
- ) is True
+ assert (
+ is_uri_allowed(
+ "viking://user/default/memories/preferences/test.md",
+ allowed_dirs,
+ allowed_patterns,
+ )
+ is True
+ )
- assert is_uri_allowed(
- "viking://user/default/memories/preferences",
- allowed_dirs,
- allowed_patterns,
- ) is True
+ assert (
+ is_uri_allowed(
+ "viking://user/default/memories/preferences",
+ allowed_dirs,
+ allowed_patterns,
+ )
+ is True
+ )
- assert is_uri_allowed(
- "viking://user/default/memories/preferences/subdir/test.md",
- allowed_dirs,
- allowed_patterns,
- ) is True
+ assert (
+ is_uri_allowed(
+ "viking://user/default/memories/preferences/subdir/test.md",
+ allowed_dirs,
+ allowed_patterns,
+ )
+ is True
+ )
def test_is_uri_allowed_by_pattern(self):
"""Test URI allowed by matching pattern."""
@@ -284,11 +297,14 @@ class TestUriValidation:
"viking://user/default/memories/preferences/{topic}.md",
}
- assert is_uri_allowed(
- "viking://user/default/memories/preferences/Python code style.md",
- allowed_dirs,
- allowed_patterns,
- ) is True
+ assert (
+ is_uri_allowed(
+ "viking://user/default/memories/preferences/Python code style.md",
+ allowed_dirs,
+ allowed_patterns,
+ )
+ is True
+ )
def test_is_uri_disallowed(self):
"""Test URI not allowed."""
@@ -297,17 +313,23 @@ class TestUriValidation:
}
allowed_patterns = set()
- assert is_uri_allowed(
- "viking://user/default/memories/other/test.md",
- allowed_dirs,
- allowed_patterns,
- ) is False
+ assert (
+ is_uri_allowed(
+ "viking://user/default/memories/other/test.md",
+ allowed_dirs,
+ allowed_patterns,
+ )
+ is False
+ )
- assert is_uri_allowed(
- "viking://user/other/memories/preferences/test.md",
- allowed_dirs,
- allowed_patterns,
- ) is False
+ assert (
+ is_uri_allowed(
+ "viking://user/other/memories/preferences/test.md",
+ allowed_dirs,
+ allowed_patterns,
+ )
+ is False
+ )
def test_is_uri_allowed_for_schema(self):
"""Test checking URI against schemas."""
@@ -321,15 +343,21 @@ class TestUriValidation:
),
]
- assert is_uri_allowed_for_schema(
- "viking://user/default/memories/preferences/test.md",
- schemas,
- ) is True
+ assert (
+ is_uri_allowed_for_schema(
+ "viking://user/default/memories/preferences/test.md",
+ schemas,
+ )
+ is True
+ )
- assert is_uri_allowed_for_schema(
- "viking://user/default/memories/other/test.md",
- schemas,
- ) is False
+ assert (
+ is_uri_allowed_for_schema(
+ "viking://user/default/memories/other/test.md",
+ schemas,
+ )
+ is False
+ )
class TestUriResolution:
@@ -341,26 +369,32 @@ class TestUriResolution:
registry = MemoryTypeRegistry()
# Add preferences schema
- registry.register(MemoryTypeSchema(
- memory_type="preferences",
- description="User preferences",
- directory="viking://user/{user_space}/memories/preferences",
- filename_template="{topic}.md",
- fields=[
- MemoryField(name="topic", field_type=FieldType.STRING, description="Topic"),
- ],
- ))
+ registry.register(
+ MemoryTypeSchema(
+ memory_type="preferences",
+ description="User preferences",
+ directory="viking://user/{user_space}/memories/preferences",
+ filename_template="{topic}.md",
+ fields=[
+ MemoryField(name="topic", field_type=FieldType.STRING, description="Topic"),
+ ],
+ )
+ )
# Add tools schema
- registry.register(MemoryTypeSchema(
- memory_type="tools",
- description="Tool memories",
- directory="viking://agent/{agent_space}/memories/tools",
- filename_template="{tool_name}.md",
- fields=[
- MemoryField(name="tool_name", field_type=FieldType.STRING, description="Tool name"),
- ],
- ))
+ registry.register(
+ MemoryTypeSchema(
+ memory_type="tools",
+ description="Tool memories",
+ directory="viking://agent/{agent_space}/memories/tools",
+ filename_template="{tool_name}.md",
+ fields=[
+ MemoryField(
+ name="tool_name", field_type=FieldType.STRING, description="Tool name"
+ ),
+ ],
+ )
+ )
return registry
@@ -439,9 +473,17 @@ class TestUriResolution:
assert len(resolved.delete_operations) == 1
# Verify resolved URIs
- assert resolved.write_operations[0].uri == "viking://user/default/memories/preferences/Write test.md"
- assert resolved.edit_operations[0].uri == "viking://agent/default/memories/tools/edit_tool.md"
- assert resolved.delete_operations[0][1] == "viking://user/default/memories/preferences/Delete me.md"
+ assert (
+ resolved.write_operations[0].uri
+ == "viking://user/default/memories/preferences/Write test.md"
+ )
+ assert (
+ resolved.edit_operations[0].uri == "viking://agent/default/memories/tools/edit_tool.md"
+ )
+ assert (
+ resolved.delete_operations[0][1]
+ == "viking://user/default/memories/preferences/Delete me.md"
+ )
def test_resolve_all_operations_with_errors(self, test_registry):
"""Test resolving operations with errors."""
@@ -466,7 +508,7 @@ class TestParseMemoryFileWithFields:
def test_parses_memory_fields_comment(self):
"""Test parsing MEMORY_FIELDS HTML comment."""
- content = '''<!-- MEMORY_FIELDS
+ content = """<!-- MEMORY_FIELDS
{
"tool_name": "web_search",
"static_desc": "Searches the web for information",
@@ -475,7 +517,7 @@ class TestParseMemoryFileWithFields:
}
-->
Here is the actual file content.
-It has multiple lines.'''
+It has multiple lines."""
result = parse_memory_file_with_fields(content)
assert result["fields"] is not None
assert result["fields"]["tool_name"] == "web_search"
@@ -500,22 +542,22 @@ It has multiple lines.'''
def test_handles_invalid_json_in_comment(self):
"""Test handles invalid JSON in MEMORY_FIELDS comment gracefully."""
- content = '''<!-- MEMORY_FIELDS
+ content = """<!-- MEMORY_FIELDS
{
"tool_name": "web_search",
invalid json here
}
-->
-File content'''
+File content"""
result = parse_memory_file_with_fields(content)
assert result["fields"] is None
assert "File content" in result["content"]
def test_removes_comment_from_content(self):
"""Test that the comment is completely removed from content."""
- content = '''Before comment
+ content = """Before comment
<!-- MEMORY_FIELDS {"test": "value"} -->
-After comment'''
+After comment"""
result = parse_memory_file_with_fields(content)
assert "<!-- MEMORY_FIELDS" not in result["content"]
assert "Before comment" in result["content"]
@@ -526,8 +568,8 @@ After comment'''
def test_fields_on_same_line(self):
"""Test MEMORY_FIELDS on single line."""
- content = '''<!-- MEMORY_FIELDS {"tool_name": "test", "value": 42} -->
-Content'''
+ content = """<!-- MEMORY_FIELDS {"tool_name": "test", "value": 42} -->
+Content"""
result = parse_memory_file_with_fields(content)
assert result["fields"] is not None
assert result["fields"]["tool_name"] == "test"
diff --git a/tests/session/memory/test_merge_ops.py b/tests/session/memory/test_merge_ops.py
index fea9678cf..3a2794e71 100644
--- a/tests/session/memory/test_merge_ops.py
+++ b/tests/session/memory/test_merge_ops.py
@@ -1,41 +1,23 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Tests for MergeOp architecture - type-safe merge operations.
"""
-import tempfile
-from pathlib import Path
-
-import pytest
-import yaml
-
from openviking.session.memory.dataclass import (
MemoryField,
- MemoryTypeSchema,
)
from openviking.session.memory.merge_op import (
+ ImmutableOp,
MergeOp,
- MergeOpBase,
MergeOpFactory,
PatchOp,
- SumOp,
- ImmutableOp,
SearchReplaceBlock,
StrPatch,
+ SumOp,
apply_str_patch,
)
from openviking.session.memory.merge_op.base import FieldType
-from openviking.session.memory.schema_model_generator import (
- SchemaModelGenerator,
- SchemaPromptGenerator,
- to_pascal_case,
-)
-from openviking.session.memory.memory_type_registry import (
- MemoryTypeRegistry,
- create_default_registry,
-)
-
# ============================================================================
# Test MergeOp Base Classes
@@ -248,13 +230,9 @@ class TestApplyStrPatch:
def test_simple_replace(self):
"""Simple replace."""
original = "hello world"
- patch = StrPatch(blocks=[
- SearchReplaceBlock(
- search="hello world",
- replace="hello there",
- start_line=1
- )
- ])
+ patch = StrPatch(
+ blocks=[SearchReplaceBlock(search="hello world", replace="hello there", start_line=1)]
+ )
result = apply_str_patch(original, patch)
# Directly test apply_str_patch
assert result == "hello there"
diff --git a/tests/session/memory/test_schema_models.py b/tests/session/memory/test_schema_models.py
index 9d0250f27..d11260d3b 100644
--- a/tests/session/memory/test_schema_models.py
+++ b/tests/session/memory/test_schema_models.py
@@ -1,10 +1,9 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for schema_models.py - dynamic Pydantic model generation."""
import tempfile
from pathlib import Path
-from typing import Union
import pytest
import yaml
@@ -13,11 +12,11 @@ from openviking.session.memory.dataclass import (
MemoryField,
MemoryTypeSchema,
)
-from openviking.session.memory.merge_op.base import FieldType, MergeOp
from openviking.session.memory.memory_type_registry import (
MemoryTypeRegistry,
create_default_registry,
)
+from openviking.session.memory.merge_op.base import FieldType, MergeOp
from openviking.session.memory.schema_model_generator import (
SchemaModelGenerator,
SchemaPromptGenerator,
@@ -82,7 +81,13 @@ class TestSchemaModelGenerator:
@pytest.fixture
def real_registry(self):
"""Create a registry with real schemas."""
- schemas_dir = Path(__file__).parent.parent.parent.parent / "openviking" / "prompts" / "templates" / "memory"
+ schemas_dir = (
+ Path(__file__).parent.parent.parent.parent
+ / "openviking"
+ / "prompts"
+ / "templates"
+ / "memory"
+ )
return create_default_registry(str(schemas_dir))
def test_create_flat_data_model(self, sample_memory_type, registry_with_sample):
@@ -224,7 +229,13 @@ class TestSchemaPromptGenerator:
@pytest.fixture
def real_registry(self):
"""Create a registry with real schemas."""
- schemas_dir = Path(__file__).parent.parent.parent.parent / "openviking" / "prompts" / "templates" / "memory"
+ schemas_dir = (
+ Path(__file__).parent.parent.parent.parent
+ / "openviking"
+ / "prompts"
+ / "templates"
+ / "memory"
+ )
return create_default_registry(str(schemas_dir))
def test_generate_type_descriptions(self, real_registry):
@@ -290,7 +301,13 @@ class TestIntegration:
def test_end_to_end_model_generation_and_validation(self):
"""Test end-to-end: load schemas, generate models, validate data."""
- schemas_dir = Path(__file__).parent.parent.parent.parent / "openviking" / "prompts" / "templates" / "memory"
+ schemas_dir = (
+ Path(__file__).parent.parent.parent.parent
+ / "openviking"
+ / "prompts"
+ / "templates"
+ / "memory"
+ )
registry = create_default_registry(str(schemas_dir))
# Create generator
diff --git a/tests/session/test_memory_dedup_actions.py b/tests/session/test_memory_dedup_actions.py
index 36aa6fe96..0a5a787ec 100644
--- a/tests/session/test_memory_dedup_actions.py
+++ b/tests/session/test_memory_dedup_actions.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
diff --git a/tests/session/test_memory_extractor_language.py b/tests/session/test_memory_extractor_language.py
index d1d980210..46bb00478 100644
--- a/tests/session/test_memory_extractor_language.py
+++ b/tests/session/test_memory_extractor_language.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import importlib.util
import sys
@@ -104,7 +104,12 @@ def test_detect_output_language_japanese_with_single_cyrillic():
def test_detect_output_language_russian_with_threshold():
"""Russian text with sufficient Cyrillic chars should be detected as Russian."""
- messages = [_msg("user", "\u042d\u0442\u043e \u0440\u0443\u0441\u0441\u043a\u0438\u0439 \u0442\u0435\u043a\u0441\u0442")]
+ messages = [
+ _msg(
+ "user",
+ "\u042d\u0442\u043e \u0440\u0443\u0441\u0441\u043a\u0438\u0439 \u0442\u0435\u043a\u0441\u0442",
+ )
+ ]
language = MemoryExtractor._detect_output_language(messages, fallback_language="en")
assert language == "ru"
diff --git a/tests/session/test_memory_extractor_response_types.py b/tests/session/test_memory_extractor_response_types.py
index ff2b26fd5..5a749dcf7 100644
--- a/tests/session/test_memory_extractor_response_types.py
+++ b/tests/session/test_memory_extractor_response_types.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Tests that memory extraction handles non-dict LLM responses gracefully.
diff --git a/tests/session/test_session_commit.py b/tests/session/test_session_commit.py
index 49c5eb2bc..d70391dd7 100644
--- a/tests/session/test_session_commit.py
+++ b/tests/session/test_session_commit.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Commit tests"""
diff --git a/tests/session/test_session_commit_race.py b/tests/session/test_session_commit_race.py
index 0583644f5..ede9754a4 100644
--- a/tests/session/test_session_commit_race.py
+++ b/tests/session/test_session_commit_race.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for session commit race condition fix (#580)."""
diff --git a/tests/session/test_session_compressor_vikingdb.py b/tests/session/test_session_compressor_vikingdb.py
index 7cb38d020..be9412ba8 100644
--- a/tests/session/test_session_compressor_vikingdb.py
+++ b/tests/session/test_session_compressor_vikingdb.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from types import SimpleNamespace
from unittest.mock import AsyncMock
diff --git a/tests/session/test_session_context.py b/tests/session/test_session_context.py
index e5f8d3fce..27785db64 100644
--- a/tests/session/test_session_context.py
+++ b/tests/session/test_session_context.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Context retrieval tests"""
diff --git a/tests/session/test_session_lifecycle.py b/tests/session/test_session_lifecycle.py
index a3258ef1b..86f834d1d 100644
--- a/tests/session/test_session_lifecycle.py
+++ b/tests/session/test_session_lifecycle.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Session lifecycle tests"""
diff --git a/tests/session/test_session_messages.py b/tests/session/test_session_messages.py
index 25f2267c7..8efcd78fc 100644
--- a/tests/session/test_session_messages.py
+++ b/tests/session/test_session_messages.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Message management tests"""
diff --git a/tests/session/test_session_usage.py b/tests/session/test_session_usage.py
index d9cc5a11c..b8a58fe89 100644
--- a/tests/session/test_session_usage.py
+++ b/tests/session/test_session_usage.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Usage record tests"""
diff --git a/tests/storage/test_collection_schemas.py b/tests/storage/test_collection_schemas.py
index da5efa7a2..4513c1e06 100644
--- a/tests/storage/test_collection_schemas.py
+++ b/tests/storage/test_collection_schemas.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import inspect
import json
diff --git a/tests/storage/test_embedding_msg_converter_tenant.py b/tests/storage/test_embedding_msg_converter_tenant.py
index 047c13cc6..0a3e08c41 100644
--- a/tests/storage/test_embedding_msg_converter_tenant.py
+++ b/tests/storage/test_embedding_msg_converter_tenant.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tenant-field backfill tests for EmbeddingMsgConverter."""
diff --git a/tests/storage/test_embedding_tracker.py b/tests/storage/test_embedding_tracker.py
index 1e3db2a9e..8b9df4ab0 100644
--- a/tests/storage/test_embedding_tracker.py
+++ b/tests/storage/test_embedding_tracker.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import asyncio
import concurrent.futures
diff --git a/tests/storage/test_semantic_dag_skip_files.py b/tests/storage/test_semantic_dag_skip_files.py
index 9a9be4fb0..8be58a640 100644
--- a/tests/storage/test_semantic_dag_skip_files.py
+++ b/tests/storage/test_semantic_dag_skip_files.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from unittest.mock import AsyncMock, MagicMock
diff --git a/tests/storage/test_semantic_dag_stats.py b/tests/storage/test_semantic_dag_stats.py
index 298d142f8..42a2966fc 100644
--- a/tests/storage/test_semantic_dag_stats.py
+++ b/tests/storage/test_semantic_dag_stats.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import asyncio
from unittest.mock import AsyncMock, MagicMock
diff --git a/tests/storage/test_vectordb_adaptor.py b/tests/storage/test_vectordb_adaptor.py
index ad1b55314..582cb28ed 100644
--- a/tests/storage/test_vectordb_adaptor.py
+++ b/tests/storage/test_vectordb_adaptor.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import os
import sys
import unittest
diff --git a/tests/test_code_hosting_utils.py b/tests/test_code_hosting_utils.py
index 41b60b527..67c048e90 100644
--- a/tests/test_code_hosting_utils.py
+++ b/tests/test_code_hosting_utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for code_hosting_utils git SSH URL support (Issue #317)."""
import importlib
diff --git a/tests/test_config_loader.py b/tests/test_config_loader.py
index 69ba6b0e7..8f7e1bc18 100644
--- a/tests/test_config_loader.py
+++ b/tests/test_config_loader.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for config_loader utilities."""
import pytest
diff --git a/tests/test_edge_cases.py b/tests/test_edge_cases.py
index 20e7e6bee..f3605d241 100644
--- a/tests/test_edge_cases.py
+++ b/tests/test_edge_cases.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Comprehensive edge case tests for OpenViking.
diff --git a/tests/test_edge_cases_simple.py b/tests/test_edge_cases_simple.py
index 92f75e246..83dfa8932 100644
--- a/tests/test_edge_cases_simple.py
+++ b/tests/test_edge_cases_simple.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Simplified edge case tests for OpenViking that don't rely on complex imports.
diff --git a/tests/test_memory_lifecycle.py b/tests/test_memory_lifecycle.py
index 35afd6fda..f5b68730f 100644
--- a/tests/test_memory_lifecycle.py
+++ b/tests/test_memory_lifecycle.py
@@ -1,15 +1,13 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for memory lifecycle hotness scoring (#296)."""
-import math
from datetime import datetime, timedelta, timezone
import pytest
from openviking.retrieve.memory_lifecycle import DEFAULT_HALF_LIFE_DAYS, hotness_score
-
NOW = datetime(2026, 2, 26, 12, 0, 0, tzinfo=timezone.utc)
diff --git a/tests/test_server_config_loader.py b/tests/test_server_config_loader.py
index ef7a69d55..56d7af866 100644
--- a/tests/test_server_config_loader.py
+++ b/tests/test_server_config_loader.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import json
diff --git a/tests/test_session_async_commit.py b/tests/test_session_async_commit.py
index ea08a1018..3ce9e7dad 100644
--- a/tests/test_session_async_commit.py
+++ b/tests/test_session_async_commit.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for async session commit support."""
diff --git a/tests/test_session_task_tracking.py b/tests/test_session_task_tracking.py
index 723742a0f..455db644c 100644
--- a/tests/test_session_task_tracking.py
+++ b/tests/test_session_task_tracking.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Integration tests for session commit task tracking via HTTP API."""
diff --git a/tests/test_task_tracker.py b/tests/test_task_tracker.py
index e000933d1..0cbe972f3 100644
--- a/tests/test_task_tracker.py
+++ b/tests/test_task_tracker.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Unit tests for TaskTracker."""
diff --git a/tests/test_telemetry_runtime.py b/tests/test_telemetry_runtime.py
index 4a8fa8448..1973103cc 100644
--- a/tests/test_telemetry_runtime.py
+++ b/tests/test_telemetry_runtime.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from __future__ import annotations
diff --git a/tests/test_upload_utils.py b/tests/test_upload_utils.py
index 6a47803d8..53def2003 100644
--- a/tests/test_upload_utils.py
+++ b/tests/test_upload_utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for shared upload utilities."""
from pathlib import Path
diff --git a/tests/transaction/conftest.py b/tests/transaction/conftest.py
index a0952289c..20183dbad 100644
--- a/tests/transaction/conftest.py
+++ b/tests/transaction/conftest.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Shared fixtures for transaction tests using real AGFS and VectorDB backends."""
import os
diff --git a/tests/transaction/test_concurrent_lock.py b/tests/transaction/test_concurrent_lock.py
index 7e25ab57b..76506c625 100644
--- a/tests/transaction/test_concurrent_lock.py
+++ b/tests/transaction/test_concurrent_lock.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for concurrent lock acquisition using real AGFS backend."""
import asyncio
diff --git a/tests/transaction/test_e2e.py b/tests/transaction/test_e2e.py
index 2f284f53d..6cdf92cb9 100644
--- a/tests/transaction/test_e2e.py
+++ b/tests/transaction/test_e2e.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""End-to-end lock tests using real AGFS backend.
These tests exercise LockContext -> LockManager -> PathLock -> AGFS,
diff --git a/tests/transaction/test_lock_context.py b/tests/transaction/test_lock_context.py
index 131fb48e5..67aa2e922 100644
--- a/tests/transaction/test_lock_context.py
+++ b/tests/transaction/test_lock_context.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for LockContext async context manager."""
import uuid
diff --git a/tests/transaction/test_lock_manager.py b/tests/transaction/test_lock_manager.py
index 83f461802..88d14f062 100644
--- a/tests/transaction/test_lock_manager.py
+++ b/tests/transaction/test_lock_manager.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for LockManager."""
import asyncio
diff --git a/tests/transaction/test_path_lock.py b/tests/transaction/test_path_lock.py
index 0b721e07e..d1840910c 100644
--- a/tests/transaction/test_path_lock.py
+++ b/tests/transaction/test_path_lock.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for path lock with fencing tokens."""
import time
diff --git a/tests/transaction/test_redo_log.py b/tests/transaction/test_redo_log.py
index 8a0def2c3..b161f0c31 100644
--- a/tests/transaction/test_redo_log.py
+++ b/tests/transaction/test_redo_log.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for RedoLog crash recovery."""
import uuid
diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py
index 819b3465d..236633478 100644
--- a/tests/unit/__init__.py
+++ b/tests/unit/__init__.py
@@ -1,2 +1,2 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
diff --git a/tests/unit/crypto/test_config.py b/tests/unit/crypto/test_config.py
index f754d80b5..b77660219 100644
--- a/tests/unit/crypto/test_config.py
+++ b/tests/unit/crypto/test_config.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Unit tests for crypto configuration.
"""
diff --git a/tests/unit/crypto/test_encryptor.py b/tests/unit/crypto/test_encryptor.py
index 31f71a023..a4f4a61f5 100644
--- a/tests/unit/crypto/test_encryptor.py
+++ b/tests/unit/crypto/test_encryptor.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Unit tests for FileEncryptor.
"""
diff --git a/tests/unit/crypto/test_exceptions.py b/tests/unit/crypto/test_exceptions.py
index 246243ab3..5614f75de 100644
--- a/tests/unit/crypto/test_exceptions.py
+++ b/tests/unit/crypto/test_exceptions.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Unit tests for crypto exception classes.
"""
diff --git a/tests/unit/crypto/test_local_provider.py b/tests/unit/crypto/test_local_provider.py
index 636a60b4f..d599e538c 100644
--- a/tests/unit/crypto/test_local_provider.py
+++ b/tests/unit/crypto/test_local_provider.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Unit tests for KeyProvider implementations.
"""
diff --git a/tests/unit/crypto/test_providers_mock.py b/tests/unit/crypto/test_providers_mock.py
index 514b4df7e..d045b5d58 100644
--- a/tests/unit/crypto/test_providers_mock.py
+++ b/tests/unit/crypto/test_providers_mock.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Mock-based unit tests for all KeyProvider implementations.
diff --git a/tests/unit/retrieve/test_retrieval_stats.py b/tests/unit/retrieve/test_retrieval_stats.py
index e9a4af687..ebfb629be 100644
--- a/tests/unit/retrieve/test_retrieval_stats.py
+++ b/tests/unit/retrieve/test_retrieval_stats.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Unit tests for retrieval statistics and observer."""
from openviking.retrieve.retrieval_stats import RetrievalStats, RetrievalStatsCollector
diff --git a/tests/unit/session/test_deduplicator_uri.py b/tests/unit/session/test_deduplicator_uri.py
index 8da1246d2..f204c7f01 100644
--- a/tests/unit/session/test_deduplicator_uri.py
+++ b/tests/unit/session/test_deduplicator_uri.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from openviking.session.memory_deduplicator import MemoryDeduplicator
diff --git a/tests/unit/session/test_memory_archiver.py b/tests/unit/session/test_memory_archiver.py
index e8d81a0b4..f8089fca7 100644
--- a/tests/unit/session/test_memory_archiver.py
+++ b/tests/unit/session/test_memory_archiver.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Unit tests for memory cold-storage archival."""
from datetime import datetime, timedelta, timezone
diff --git a/tests/unit/stats/test_stats_aggregator.py b/tests/unit/stats/test_stats_aggregator.py
index fb6457d50..5f0e26473 100644
--- a/tests/unit/stats/test_stats_aggregator.py
+++ b/tests/unit/stats/test_stats_aggregator.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for StatsAggregator."""
from datetime import datetime, timedelta, timezone
diff --git a/tests/unit/stats/test_stats_api.py b/tests/unit/stats/test_stats_api.py
index fd81f8c8d..fc82f50ac 100644
--- a/tests/unit/stats/test_stats_api.py
+++ b/tests/unit/stats/test_stats_api.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for the stats API router."""
from unittest.mock import AsyncMock, MagicMock, patch
diff --git a/tests/unit/test_circuit_breaker.py b/tests/unit/test_circuit_breaker.py
index 0528abc0f..9916f608e 100644
--- a/tests/unit/test_circuit_breaker.py
+++ b/tests/unit/test_circuit_breaker.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Comprehensive tests for circuit breaker utility."""
diff --git a/tests/unit/test_cohere_embedder.py b/tests/unit/test_cohere_embedder.py
index 05706b45c..828841354 100644
--- a/tests/unit/test_cohere_embedder.py
+++ b/tests/unit/test_cohere_embedder.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for Cohere embedder support."""
from unittest.mock import MagicMock, patch
diff --git a/tests/unit/test_cohere_rerank.py b/tests/unit/test_cohere_rerank.py
index 0e1c7eadb..b06fd2aa7 100644
--- a/tests/unit/test_cohere_rerank.py
+++ b/tests/unit/test_cohere_rerank.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for Cohere rerank client."""
from unittest.mock import MagicMock, patch
diff --git a/tests/unit/test_context.py b/tests/unit/test_context.py
index 439583272..f41f459b4 100644
--- a/tests/unit/test_context.py
+++ b/tests/unit/test_context.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Comprehensive tests for Context class."""
diff --git a/tests/unit/test_embedding_config_gemini.py b/tests/unit/test_embedding_config_gemini.py
index c09782159..9208c6a72 100644
--- a/tests/unit/test_embedding_config_gemini.py
+++ b/tests/unit/test_embedding_config_gemini.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Unit tests for Gemini-specific EmbeddingModelConfig and EmbeddingConfig behavior."""
from unittest.mock import patch
diff --git a/tests/unit/test_embedding_config_voyage.py b/tests/unit/test_embedding_config_voyage.py
index 15c84e071..eef0f0f27 100644
--- a/tests/unit/test_embedding_config_voyage.py
+++ b/tests/unit/test_embedding_config_voyage.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for Voyage embedding configuration."""
import pytest
diff --git a/tests/unit/test_embedding_vectorize_strategy.py b/tests/unit/test_embedding_vectorize_strategy.py
index 53aca0727..7bbb2c28c 100644
--- a/tests/unit/test_embedding_vectorize_strategy.py
+++ b/tests/unit/test_embedding_vectorize_strategy.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import pytest
diff --git a/tests/unit/test_extra_headers_embedding.py b/tests/unit/test_extra_headers_embedding.py
index c766debb0..91e2b7a90 100644
--- a/tests/unit/test_extra_headers_embedding.py
+++ b/tests/unit/test_extra_headers_embedding.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for extra_headers support in OpenAIDenseEmbedder and EmbeddingConfig factory.
Covers:
diff --git a/tests/unit/test_extra_headers_vlm.py b/tests/unit/test_extra_headers_vlm.py
index 1d5bdafbd..97f6bea00 100644
--- a/tests/unit/test_extra_headers_vlm.py
+++ b/tests/unit/test_extra_headers_vlm.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for VLM extra_headers support."""
from unittest.mock import AsyncMock, MagicMock, patch
diff --git a/tests/unit/test_gemini_embedder.py b/tests/unit/test_gemini_embedder.py
index a6dbc06d9..97413d39e 100644
--- a/tests/unit/test_gemini_embedder.py
+++ b/tests/unit/test_gemini_embedder.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Tests for GeminiDenseEmbedder.
Pattern: patch at module import path, use MagicMock, never make real API calls.
diff --git a/tests/unit/test_jina_embedder.py b/tests/unit/test_jina_embedder.py
index e631062f6..06360c0d6 100644
--- a/tests/unit/test_jina_embedder.py
+++ b/tests/unit/test_jina_embedder.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for Jina AI Embedder"""
from unittest.mock import MagicMock, patch
diff --git a/tests/unit/test_litellm_embedder.py b/tests/unit/test_litellm_embedder.py
index a664e1a2b..5796f7fed 100644
--- a/tests/unit/test_litellm_embedder.py
+++ b/tests/unit/test_litellm_embedder.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for LiteLLM Embedder and factory integration."""
from unittest.mock import MagicMock, patch
diff --git a/tests/unit/test_message.py b/tests/unit/test_message.py
index 483fb60f5..901184f3d 100644
--- a/tests/unit/test_message.py
+++ b/tests/unit/test_message.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Comprehensive tests for Message and Part classes."""
diff --git a/tests/unit/test_minimax_embedder_simple.py b/tests/unit/test_minimax_embedder_simple.py
index 5602e2cb8..6b853bcc9 100644
--- a/tests/unit/test_minimax_embedder_simple.py
+++ b/tests/unit/test_minimax_embedder_simple.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for MiniMax Embedder (Simple)"""
import os
diff --git a/tests/unit/test_ollama_embedding_factory.py b/tests/unit/test_ollama_embedding_factory.py
index d2b3caf17..637ae27f1 100644
--- a/tests/unit/test_ollama_embedding_factory.py
+++ b/tests/unit/test_ollama_embedding_factory.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for the ollama embedding factory in EmbeddingConfig._create_embedder.
Regression tests for two bugs fixed in the ollama factory lambda:
@@ -9,7 +9,6 @@ Regression tests for two bugs fixed in the ollama factory lambda:
with the openai factory and the placeholder used inside OpenAIDenseEmbedder.
"""
-import pytest
from unittest.mock import MagicMock, patch
from openviking_cli.utils.config.embedding_config import EmbeddingConfig, EmbeddingModelConfig
diff --git a/tests/unit/test_openai_embedder.py b/tests/unit/test_openai_embedder.py
index 02df2a23b..e9e20ad80 100644
--- a/tests/unit/test_openai_embedder.py
+++ b/tests/unit/test_openai_embedder.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for OpenAI Embedder"""
from unittest.mock import MagicMock, patch
diff --git a/tests/unit/test_process_lock.py b/tests/unit/test_process_lock.py
index 05b60882e..b5774b496 100644
--- a/tests/unit/test_process_lock.py
+++ b/tests/unit/test_process_lock.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for PID-based process lock utility."""
diff --git a/tests/unit/test_skill_processor_none.py b/tests/unit/test_skill_processor_none.py
index 1681ec28b..d5e3ee26d 100644
--- a/tests/unit/test_skill_processor_none.py
+++ b/tests/unit/test_skill_processor_none.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for SkillProcessor None data handling.
Verifies that SkillProcessor raises a clear ValueError when
diff --git a/tests/unit/test_stream_config_vlm.py b/tests/unit/test_stream_config_vlm.py
index faf5b6e25..64b2f81c2 100644
--- a/tests/unit/test_stream_config_vlm.py
+++ b/tests/unit/test_stream_config_vlm.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for VLM stream configuration support."""
from unittest.mock import MagicMock, patch
diff --git a/tests/unit/test_time_utils_comprehensive.py b/tests/unit/test_time_utils_comprehensive.py
index e84432e33..2e9b485b1 100644
--- a/tests/unit/test_time_utils_comprehensive.py
+++ b/tests/unit/test_time_utils_comprehensive.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Comprehensive tests for time utility functions."""
diff --git a/tests/unit/test_uri_short_format.py b/tests/unit/test_uri_short_format.py
index b4315ef7f..35b28e027 100644
--- a/tests/unit/test_uri_short_format.py
+++ b/tests/unit/test_uri_short_format.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for VikingURI short-format URI normalization.
Verifies that VikingURI accepts short-format paths (e.g., '/resources',
diff --git a/tests/unit/test_vlm_response_formats.py b/tests/unit/test_vlm_response_formats.py
index 14be204c5..007b24b86 100644
--- a/tests/unit/test_vlm_response_formats.py
+++ b/tests/unit/test_vlm_response_formats.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for VLM response format handling (Issue #801)."""
from types import SimpleNamespace
@@ -50,14 +50,12 @@ class TestVLMBaseResponseFormats:
)
def test_extract_content_from_str_response(self, vlm):
- assert vlm._extract_content_from_response("plain string response") == "plain string response"
+ assert (
+ vlm._extract_content_from_response("plain string response") == "plain string response"
+ )
def test_extract_content_from_standard_openai_response(self, vlm):
response = SimpleNamespace(
- choices=[
- SimpleNamespace(
- message=SimpleNamespace(content="standard response content")
- )
- ]
+ choices=[SimpleNamespace(message=SimpleNamespace(content="standard response content"))]
)
assert vlm._extract_content_from_response(response) == "standard response content"
diff --git a/tests/unit/test_vlm_thinking_param.py b/tests/unit/test_vlm_thinking_param.py
index 8628df682..b5415d2e2 100644
--- a/tests/unit/test_vlm_thinking_param.py
+++ b/tests/unit/test_vlm_thinking_param.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for LiteLLM thinking parameter scoping to DashScope providers."""
from openviking.models.vlm.backends.litellm_vlm import LiteLLMVLMProvider
diff --git a/tests/unit/test_voyage_embedder.py b/tests/unit/test_voyage_embedder.py
index 1a49f4281..a508639a5 100644
--- a/tests/unit/test_voyage_embedder.py
+++ b/tests/unit/test_voyage_embedder.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for Voyage AI embedder support."""
from unittest.mock import MagicMock, patch
diff --git a/tests/unit/tool_skill/test_tool_skill_calibration.py b/tests/unit/tool_skill/test_tool_skill_calibration.py
index 6352f6b05..1278d977e 100644
--- a/tests/unit/tool_skill/test_tool_skill_calibration.py
+++ b/tests/unit/tool_skill/test_tool_skill_calibration.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Tests for tool/skill name calibration in memory extraction."""
from openviking.message.part import ToolPart
diff --git a/tests/unit/tool_skill/test_tool_skill_memory_guardrails.py b/tests/unit/tool_skill/test_tool_skill_memory_guardrails.py
index 49fbd3e1f..a82394797 100644
--- a/tests/unit/tool_skill/test_tool_skill_memory_guardrails.py
+++ b/tests/unit/tool_skill/test_tool_skill_memory_guardrails.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
diff --git a/tests/unit/tool_skill/test_tool_skill_utils.py b/tests/unit/tool_skill/test_tool_skill_utils.py
index cfaf63548..6f54883cd 100644
--- a/tests/unit/tool_skill/test_tool_skill_utils.py
+++ b/tests/unit/tool_skill/test_tool_skill_utils.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
from openviking.message.part import ToolPart
from openviking.session.tool_skill_utils import (
diff --git a/tests/utils/mock_context.py b/tests/utils/mock_context.py
index 99cc7a6de..0b3971274 100644
--- a/tests/utils/mock_context.py
+++ b/tests/utils/mock_context.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""Mock context utilities for testing"""
diff --git a/tests/utils/test_circuit_breaker.py b/tests/utils/test_circuit_breaker.py
index 0b4874059..db3bb51eb 100644
--- a/tests/utils/test_circuit_breaker.py
+++ b/tests/utils/test_circuit_breaker.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import threading
import time
diff --git a/tests/vectordb/test_bytes_row.py b/tests/vectordb/test_bytes_row.py
index 906aa0b45..650f1e438 100644
--- a/tests/vectordb/test_bytes_row.py
+++ b/tests/vectordb/test_bytes_row.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import json
import random
import string
diff --git a/tests/vectordb/test_collection_large_scale.py b/tests/vectordb/test_collection_large_scale.py
index 867358c6d..39820507c 100644
--- a/tests/vectordb/test_collection_large_scale.py
+++ b/tests/vectordb/test_collection_large_scale.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
"""
Large scale scenario tests - Collection stress tests and performance tests
Tests for large data volumes, high-dimensional vectors, complex queries, etc.
diff --git a/tests/vectordb/test_crash_recovery.py b/tests/vectordb/test_crash_recovery.py
index 2e734332c..d05a2dd7e 100644
--- a/tests/vectordb/test_crash_recovery.py
+++ b/tests/vectordb/test_crash_recovery.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import multiprocessing
import os
import shutil
diff --git a/tests/vectordb/test_data_processor.py b/tests/vectordb/test_data_processor.py
index c13f37bf5..a0fb2367f 100644
--- a/tests/vectordb/test_data_processor.py
+++ b/tests/vectordb/test_data_processor.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import shutil
import unittest
diff --git a/tests/vectordb/test_filter_ops.py b/tests/vectordb/test_filter_ops.py
index ccc305381..f5cf6ae19 100644
--- a/tests/vectordb/test_filter_ops.py
+++ b/tests/vectordb/test_filter_ops.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import gc
import random
diff --git a/tests/vectordb/test_openviking_vectordb.py b/tests/vectordb/test_openviking_vectordb.py
index 0562a97b7..a4de5cc42 100644
--- a/tests/vectordb/test_openviking_vectordb.py
+++ b/tests/vectordb/test_openviking_vectordb.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import shutil
import unittest
diff --git a/tests/vectordb/test_project_group.py b/tests/vectordb/test_project_group.py
index ddc8f19b8..64934705f 100644
--- a/tests/vectordb/test_project_group.py
+++ b/tests/vectordb/test_project_group.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import os
import shutil
import unittest
diff --git a/tests/vectordb/test_pydantic_validation.py b/tests/vectordb/test_pydantic_validation.py
index 66d9f41e1..f08c8091b 100644
--- a/tests/vectordb/test_pydantic_validation.py
+++ b/tests/vectordb/test_pydantic_validation.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import os
import sys
diff --git a/tests/vectordb/test_recall.py b/tests/vectordb/test_recall.py
index a38761ebe..6d8c1d810 100644
--- a/tests/vectordb/test_recall.py
+++ b/tests/vectordb/test_recall.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import random
import shutil
import unittest
diff --git a/tests/vectordb/test_vikingdb_project.py b/tests/vectordb/test_vikingdb_project.py
index 06dee950d..94f821128 100644
--- a/tests/vectordb/test_vikingdb_project.py
+++ b/tests/vectordb/test_vikingdb_project.py
@@ -1,5 +1,5 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: Apache-2.0
+# SPDX-License-Identifier: AGPL-3.0
import unittest
from openviking.storage.vectordb.project.vikingdb_project import get_or_create_vikingdb_project